Jwt整合Secirity实现用户登陆(拿捏篇)

本篇介绍最简单的Security整合Jwt实现用户登入
根据上几篇文章的哦!!!
不明白的可以看上几篇文章看下

创建Jwt工具类

JwtUtil类

public class JwtUtil {

        public static final String TOKEN_HEADER = "Authorization";
        public static final String TOKEN_PREFIX = "HE ";
        public static final String SECRET = "jwtsecret";
        public static final String ISS = "echisan";

        private static final Long EXPIRATION = 60 * 60 * 3L; //过期时间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();
            }
            return claims;
        }

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


配置用户资源处理器

jwtAccessDeniedHandler

@Component
public class jwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException, IOException {
        System.out.println("用户访问没有授权资源");
        System.out.println(e.getMessage());
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e==null? String.valueOf(ResultUtil.Error(401,"用户没有授权")) :e.getMessage());

    }
}

配置用户资源授权处理

JwtAuthentication类 实现AuthenticationEntryPoint

@Component
public class JwtAuthentication implements AuthenticationEntryPoint{
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        System.out.println("用户访问资源没有携带正确的token");
        System.out.println(e.getMessage());
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e == null ? "用户访问资源没有携带正确的token" : e.getMessage());
    }
}

配置Jwt的Filter

创建一个FIlter来进行过滤Jwt的token

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String tokenHead=request.getHeader(JwtUtil.TOKEN_HEADER);
        if(tokenHead==null|| !tokenHead.startsWith(JwtUtil.TOKEN_PREFIX)){
            chain.doFilter(request,response);
            return;
        }
        if(!JwtUtil.isExpiration(tokenHead.replace(JwtUtil.TOKEN_PREFIX,""))){
            //设置上下文
            UsernamePasswordAuthenticationToken authentication = getAuthentication(tokenHead);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        super.doFilterInternal(request, response, chain);
    }

    //获取用户信息
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader){
        String token = tokenHeader.replace(JwtUtil.TOKEN_PREFIX, "");
        String username = JwtUtil.getUserName(token);
        // 获得权限 添加到权限上去
        String role = JwtUtil.getUserRole(token);
        List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
        roles.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return role;
            }
        });
        if(username != null){
            return new UsernamePasswordAuthenticationToken(username, null,roles);
        }
        return null;
    }


    public JwtAuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager, authenticationEntryPoint);
    }
}

在Security上面进行配置Filter

下面上SecurityConfig的配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
userDetailsService userDetailsService;
    @Autowired
    private jwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**")
                .permitAll()
                .antMatchers("/").permitAll()
                //login 不拦截
                .antMatchers("/login").permitAll()

                .anyRequest().authenticated()
                //授权
                .and()
                // 禁用session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 使用自己定义的拦截机制,拦截jwt
        http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                //授权错误信息处理
                .exceptionHandling()
                //用户访问资源没有携带正确的token
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                //用户访问没有授权资源
                .accessDeniedHandler(jwtAccessDeniedHandler);

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        //使用的密码比较方式
        return new BCryptPasswordEncoder();
    }
}

大功告成,这样就完成了整合

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fails逆向

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值