Spring Security 将JWT编码字符串转换为JwtAuthenticationToken

fv2wmkja  于 2023-04-06  发布在  Spring
关注(0)|答案(1)|浏览(233)

我有一个表示JWT token的String,例如.'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lliwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ',我想将它转换为org.springframework.security.oauth2.jwt.Jwt类或JwtAuthenticationToken的示例。我如何才能做到这一点?

e1xvtsh3

e1xvtsh31#

您可以使用Spring Security的JwtDecoder来解码JWT令牌并创建一个`JwtAuthenticationToken示例。
下面是一个例子:

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.oauth2.jwt.Jwt;
    import org.springframework.security.oauth2.jwt.JwtDecoder;
    import org.springframework.security.oauth2.jwt.JwtException;
    import org.springframework.security.oauth2.jwt.JwtValidationException;
    import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
    
    import java.util.Collections;
    
    public class JwtUtils {
    
        public static Authentication getAuthenticationFromJwtToken(String jwtToken) throws JwtException {
            JwtDecoder jwtDecoder = new NimbusJwtDecoder(); 
            Jwt jwt = jwtDecoder.decode(jwtToken);

            String username = jwt.getSubject();
            String[] authorities = jwt.getClaimAsStringArray("authorities");

            return new UsernamePasswordAuthenticationToken(
                    username,
                    null,
                    Collections.singletonList(new SimpleGrantedAuthority(authorities[0]))
            );
        }
    }

这里有一些你应该阅读的资源:

相关问题