栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【java】springboot spring security + JWT鉴权

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【java】springboot spring security + JWT鉴权

一些理解,不一定正确

请求通过API,进入Basic Authentication Filter,在这里拿到token,解析token,拿到username和password,将用户输入的用户名密码进行封装,并提供给AuthenticationManager.authenticate()方法进行验证,验证成功后,返回一个认证成功的UsernamePasswordAuthenticationToken(Authentication)对象,然后放在security的context中,继续过滤链。

如果没有token,或者token不对,则继续过滤链,到达UsernamePasswordAuthenticationFilter,在attemptAuthentication()方法中,从请求的header中,拿到user和password,调用AuthenticationManager.authenticate()进行认证

AuthenticationManager验证过程

AuthenticationManager.authenticate()接收Authentication对象作为参数,由其实现类ProviderManager完成对其进行验证

在ProviderManager的authenticate方法中,轮训成员变量List providers。该providers中如果有一个

AuthenticationProvider的supports函数返回true,那么就会调用该AuthenticationProvider的authenticate函数认证,调用SecurityConfig中指定的userService,没有则使用UserDetailsService ,调用loadUserByUsername() 方法从数据库中加载用户信息 ,对密码等进行验证,整个认证过程结束。如果不成功,则继续使用下一个合适的AuthenticationProvider进行认证,只要有一个认证成功则为认证成功。

参考大佬的验证原理

代码

spring security + JWT依赖

        
            org.springframework.boot
            spring-boot-starter-security
        
        
            com.auth0
            java-jwt
            3.19.2
        

创建SecurityConfig类,配置springSecurity

package xyz.heguchangan.easymusicapp.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import xyz.heguchangan.easymusicapp.exception.RestAuthenticationEntryPoint;
import xyz.heguchangan.easymusicapp.filter.JwtAuthenticationFilter;
import xyz.heguchangan.easymusicapp.filter.JwtAuthorizationFilter;
import xyz.heguchangan.easymusicapp.service.UserService;


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    public static final String SECRET = "heguchangan";

    
    public static final long EXPIRATION_TIME = 864000000;

    
    public static final String TOKEN_PREFIX = "Bearer";

    
    public static final String HEADER_STRING = "Authorization";

    
    public static final String SIGN_UP_URL = "/users/";

    
    
    UserService userService;
    RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    
    @Autowired
    public void setRestAuthenticationEntryPoint(RestAuthenticationEntryPoint restAuthenticationEntryPoint) {
        this.restAuthenticationEntryPoint = restAuthenticationEntryPoint;
    }
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        http.cors()
                .and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST,SIGN_UP_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JwtAuthenticationFilter(authenticationManager()))
                .addFilter(new JwtAuthorizationFilter(authenticationManager()))
                .exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        
        authenticationManagerBuilder.userDetailsService(userService);
    }
}

两个过滤器

JwtAuthorizationFilter

package xyz.heguchangan.easymusicapp.filter;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import xyz.heguchangan.easymusicapp.config.SecurityConfig;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;


public class JwtAuthorizationFilter extends BasicAuthenticationFilter {
    //构造函数
    public JwtAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 拿到header中的token
        String token = request.getHeader(SecurityConfig.HEADER_STRING);
        //没有header,或者token不是规定的前缀
        if(token == null || !token.startsWith(SecurityConfig.TOKEN_PREFIX)){
            // 不做处理,给下一个过滤器,还可以通过username和password进行鉴权
            chain.doFilter(request,response);
            return;
        }

        // 进行鉴权,拿到鉴权之后的Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(token);
        // 把Authentication对象放在security的context中,继续过滤链
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request,response);

    }
    
    private UsernamePasswordAuthenticationToken getAuthentication(String header){
        if (header != null) {
            
            String username = JWT.require(Algorithm.HMAC512(SecurityConfig.SECRET))
                    .build()
                    .verify(header.replace(SecurityConfig.TOKEN_PREFIX, ""))
                    .getSubject();
            if (username != null) {
                
                User user = userService.loadUserByUsername(username);
                return new UsernamePasswordAuthenticationToken(username, user.getPassword(), new ArrayList<>());
            }
        }
        return null;
    }
}

JwtAuthenticationFilter

该拦截器通过username和password进行鉴权

package xyz.heguchangan.easymusicapp.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import xyz.heguchangan.easymusicapp.config.SecurityConfig;
import xyz.heguchangan.easymusicapp.entity.User;
import xyz.heguchangan.easymusicapp.exception.BizException;
import xyz.heguchangan.easymusicapp.exception.ExceptionType;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;


// 因为是针对username 和password 所以继承UsernamePasswordAuthenticationFilter类
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    
    private final AuthenticationManager authenticationManager;
    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            
            //从输入流中映射json对应的属性给user对象,就是把json转换成user对象
            User user = new ObjectMapper().
                    readValue(request.getInputStream(),User.class);
            // 通过username和pwd生成token,对token鉴权返回结果
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            user.getUsername(),
                            user.getPassword(),
                            new ArrayList<>()
                    )
            );
        } catch (IOException e) {
            e.printStackTrace();
            
            throw new BizException(ExceptionType.FORBIDDEN);
        }
    }

    
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        
        String token = JWT.create()
                .withSubject(((User)authResult.getPrincipal()).getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis()+ SecurityConfig.EXPIRATION_TIME))
                .sign(Algorithm.HMAC512(SecurityConfig.SECRET));
        
        response.addHeader(SecurityConfig.HEADER_STRING,SecurityConfig.TOKEN_PREFIX+token);
    }
}

UserService

springSecurity底层需要访问数据库,需要继承UserDetailsService,实现loadUserByUsername方法

public interface UserService extends UserDetailsService {

    
    @Override
    User loadUserByUsername(String username) throws UsernameNotFoundException;

}

同时 user类需要实现UserDetails

public class User implements UserDetails {

	....

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937583.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号