>Java >java지도 시간 >SpringBoot가 JWT를 결합하여 로그인 권한 제어를 구현하는 방법

SpringBoot가 JWT를 결합하여 로그인 권한 제어를 구현하는 방법

WBOY
WBOY앞으로
2023-05-20 11:01:061199검색

first는 사용 된 JWT 패키지를 가져와야합니다. . JWTAuthenticationFilter(로그인 확인), JWTAuthorizationFilter(권한 식별) 및 UserDetailsServiceImpl 클래스(계정 비밀번호와 일치하는지 데이터베이스 확인) 준비

1.JWTAuthenticationFilter.java(로그인 확인)

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.8.0</version>
</dependency>

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.2.0</version>
</dependency>

2.JWTAuthorizationFilter.java(권한 식별)

public class LoginUser {
    private Integer userId;
    private String username;
    private String password;
    private String role;

    生成getter和setter......

}

3.UserDetailsServiceImpl.java (계정 비밀번호가 일치하는지 데이터베이스 확인)

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Collections;

public class JwtUser implements UserDetails{
    private Integer id;
    private String username;
    private String password;
    private Collection<? extends GrantedAuthority> authorities;

    public JwtUser(){
    }

    public JwtUser(LoginUser loginUser){
        this.id = loginUser.getUserId();
        this.username = loginUser.getUsername();
        this.password = loginUser.getPassword();
        authorities = Collections.signleton(new SimpleGrantedAuthority(loginUser.getRole()));
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(){
        return authorities;
    }

    @Override
    public String getPassword(){
        return password;
    }

    @Override
    public String getUsername(){
        return username;
    }

    //账号是否未过期
    @Override
    public boolean isAccountNonExpired(){
        return true;
    }

    //账号是否未锁定
    @Override
    public boolean isAccountNonLocked(){
        return true
    }

    //账号凭证是否未过期
    @Override
    public boolean isCredentialsNonExpired(){
        return true;
    }

    @Override
    public boolean isEnabled(){
        return true;
    }

    
}

Four.FailHandler (계정 비밀번호가 잘못된 경우 처리 방법)

import com.bean.JwtUser;
import io.jsonwebtoken.*;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtils {
    
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    public static final String SECRET = "jwtsecret";
    public static final String ISS = "echisan";

    private static final Long EXPIRATION = 60 * 60 * 3;//过期时间3小时
    private static final String ROLE = "role";

    //创建token
    public static String createToken(String username, String role, boolean isRememberMe){
        Map map = new HashMap();
        map.put(ROLE, role);
        return Jwts.builder()
                 .signWith(SignatureAlgorithm.HS512, SECRET)
                 .setClaims(map)
                 .setIssuer(ISS)
                 .setSubject(username)
                 .setIssuedAt(new Date())
                 .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                 .compact();
    }

    //从token中获取用户名(此处的token是指去掉前缀之后的)
    public static String getUserName(String token){
        String username;
        try {
            username = getTokenBody(token).getSubject();
        } catch (    Exception e){
            username = null;
        }
        return username;
    }

    public static String getUserRole(String token){
        return (String) getTokenBody(token).get(ROLE);
    }

    private static Claims getTokenBody(String token){
        Claims claims = null;
        try{
            claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
        } catch(ExpiredJwtException e){
            e.printStackTrace();
        } catch(UnsupportedJwtException e){
            e.printStackTrace();
        } catch(MalformedJwtException e){
            e.printStackTrace();
        } catch(SignatureException e){
            e.printStackTrace();
        } catch(IllegalArgumentException e){
            e.printStackTrace();
        }
    }

    //是否已过期
    public static boolean isExpiration(String token){
        try{
            return getTokenBody(token).getExpiration().before(new Date());
        } catch(Exception e){
            e.printStackTrace;
        }
        return true;
    }
}

Five.Configure SecurityConfig

권한에 대한 관련 정보를 규정하는 클래스입니다

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager){
        this.authenticationManager = authenticationManager;
        setAuthenticationFailureHandler(new FailHandler());//设置账号密码错误时的处理方式
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException{
        //从输入流中获取登录的信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        return authenticationManager.authenticate(
                       new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>())
        );
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                              HttpServletResponse response, FilterChain chain, Authentication authResult
) throws IOException, ServletException{
        JwtUser jwtUser = (JwtUser) authResult.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = jwtUser.getAuthorities();
        String role = "";
        for(GrantedAuthority authority : authorities){
            role = authority.getAuthority();
        }
        String token = JwtTokenUtils.createToken(jwtUser.getUsername, role, false);
        //返回创建成功的token
        //但是这里创建的token只是单纯的token,按照jwt的规定,
        //最后请求的格式应该是 “Bearer token“。
        response.addHeader(JwtTokenUtils.TOKEN_HEADER, JwtTokenUtils.TOKEN_PREFIX + token);
    }

    //@Override
    //protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
    //                          AuthenticationException failed) throws IOException, ServletException {
    //    response.getWriter().write("authentication failed, reason: " + failed.getMessage());
    //}
}

위 내용은 SpringBoot가 JWT를 결합하여 로그인 권한 제어를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제