全面前后端分离项目中springSecurity集成jwt的认证搭建 (springboot)

在前后端分离场景中的权限系统如何构建?

	公司需要去专门做一套权限相关的系统,可是网上有关spring-security的很多教程要么是基于内存使用的,要么是前后端不分离的,将登陆静态页
面直接放在项目目录下面,这和现在大多数的需求是不同的,今天做到这就专门写一篇博客来记录一下吧。
	先分析一下,因为是前后端分离的开发,所以其实后端是完全和前端页面是脱离开的。前后端通过json去相互传递数据。后端需要做的就是使用JWT去
生成一个令牌去给到前端人员,后续的认证工作都用这个令牌去操作就行了。关于页面跳转等问题其实不是我们后端开发需要考虑的事情。
	好的,废话不多说,直接开造了。
	框架方面的介绍这边就不赘述了,可以去网上看看。

配置spring-security

      第一步需要去配置一个spring security,配置它的放行的资源等等.这里其实很简单,我直接把代码粘进来。
  • curityConfig 配置类
@Configuration // springboot的配置注解
@EnableWebSecurity // 启用spring-securiity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired // 这里是登录时的自定义登录逻辑
    private UserSecurityService userSecurityService;

    @Autowired // 这里是登录成功后走的逻辑
    private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
    @Autowired // 登录失败走的逻辑
    private RestAuthenticationFailureHandler restAuthenticationFailureHandler;
    @Autowired // 退出登录成功后的逻辑
    private RestLogoutSuccessHandler restLogoutSuccessHandler;

    @Autowired // 没有登录就去访问资源的时候走的逻辑
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 禁用CSRF保护
                .csrf().disable()

                .authorizeRequests()
                // 配置那些路径可以不用权限访问(我这里配置了用户登录,用户注册,和swagger相关的资源)
                .antMatchers("/user/login", "/user/register",
                        "/swagger-ui.html",
                        "/v2/**",
                        "/webjars/**",
                        "/swagger-resources/**",
                        "/swagger-ui.html/**"
                ).permitAll()

                // 剩下的任何访问都必须授权
                .anyRequest()
                .fullyAuthenticated()

                .and()
                // 配置登录相关的配置
                .formLogin()
                // 用户登录接口(框架内部的接口,不用我们自己写)
                .loginProcessingUrl("/user/login")
                // 用户名和密码的命名(默认的是username,password,我比较喜欢驼峰样式所以手动改了一下)
                .usernameParameter("userName")
                .passwordParameter("passWord")
                // 登陆成功后的处理,因为是API的形式所以不用跳转页面
                .successHandler(restAuthenticationSuccessHandler)
                // 登陆失败后的处理
                .failureHandler(restAuthenticationFailureHandler)

                .and()
                // 登出后的处理(框架内部接口)
                .logout().logoutUrl("/user/logout")
                // 登出后的处理
                .logoutSuccessHandler(restLogoutSuccessHandler)

                .and()
                // 认证不通过后的处理
                .exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)

                .and()
                // 增加一个jwt的校验过滤器,用于去校验jwt
                .addFilter(
                        new JWTAuthenticationFilter(authenticationManager(), userSecurityService));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 指定登录的时候走我们的自定义登录逻辑
        auth.userDetailsService(userSecurityService);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Bean
    // 这里是官方推荐的加密算法
    public BCryptPasswordEncoder bcryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

上面配置中涉及的几个类,我一一粘出来

  • UserSecurityService 自定义登录逻辑
@Service
@Slf4j
public class UserSecurityService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    /**
     * 自定义登录逻辑
     *
     * @author
     * @date 2021/3/29 13:43
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    // 这边要换成自己的查询数据库操作
        User user = userMapper.queryByName(userName);
        if (user == null) {
            throw new UsernameNotFoundException(ValidateMessage.USER_NAME_NOTFIND);
        }
        // 通过roleId查询role
        Role role =roleMapper.queryById(user.getRoleId());
        return new LoginUserDTO(user.getName(),
                user.getPassWord(),
                AuthorityUtils.createAuthorityList(role.getName()), user.getUserId());
    }

}
  • RestAuthenticationEntryPoint 未登录用户访问处理逻辑
/*
 * AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常
 */
@Slf4j
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {
        log.error(authException.getMessage());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(
        // 这里返回的是一个自动以异常,包含一个异常状态码和一个异常信息
                JSONObject.toJSONString(Result.failed(new AppException(ErrorCode.USER_NOT_LOGIN,"用户未登录,请登录后重试!"))));
        response.flushBuffer();
    }

}

  • RestAuthenticationSuccessHandler 登录成功后的逻辑

/**
 * 登陆成功处理
 * 
 * @author lenovo
 * 
 *         2019年7月29日
 */
@Slf4j
@Component
public class RestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Autowired
    // 这是用户相关的
    private UserMapper userMapper;

   // JWT过期时间 这里设置的是7天
    private final Long expiration=1000*7*24*60*60;


    // JWT加密密钥 可以自定义
    private String secret= "PwcJwtSecret";



    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws ServletException, IOException {
        clearAuthenticationAttributes(request);
       User user = userMapper.queryByName(authentication.getName());
        String authorization = Constants.REQUEST_HEAD_PREFIX + AuthenticationUtil
                .generateAuthentication(secret,
                        new Date(System.currentTimeMillis() + expiration*1000),
                        ((LoginUserDTO) authentication.getPrincipal()).getUsername());
        LoginResponseDto loginResponseDto =
                new LoginResponseDto(authorization, user.getUserId(),user.getName(), null, null);
        Result<LoginResponseDto> result = Result.success(loginResponseDto);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().append(JSONObject.toJSONString(result));
        response.flushBuffer();

    }
}

  • RestAuthenticationFailureHandler 登录失败后的逻辑
/**
 * 登录失败处理
 * 
 * @author lenovo
 * 
 *         2019年7月29日
 */
@Slf4j
@Component
public class RestAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Result<Object> result = null;
        if (exception instanceof BadCredentialsException) {
        	result = Result.failed(ErrorCode.ERROR_CODE_FOR_LOGIN,
                    Constants.MESSAGE_ERROR_FOR_USER, null);
		}else {
	        result = Result.failed(ErrorCode.ERROR_CODE_FOR_LOGIN,
	                Constants.MESSAGE_ERROR_FOR_LOGIN, null);
	    }
        response.getWriter().append(JSONObject.toJSONString(result));
        response.flushBuffer();
    }
}

  • 退出成功后的逻辑 RestLogoutSuccessHandler
**
 * 退出登录处理
 */
@Slf4j
@Component
public class RestLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        response.getWriter().append(JSONObject.toJSONString(Result.success()));

        response.flushBuffer();
    }
}

  • JWT过滤器逻辑
/**
 * token的校验 该类继承自BasicAuthenticationFilter,在doFilterInternal方法中, 从http头的Authorization
 * 项读取token数据,然后用Jwts包提供的方法校验token的合法性。 如果校验通过,就认为这是一个取得授权的合法请求
 * UsernamePasswordAuthenticationFilter
 * UserAuthenticationFilter
 */
@Getter
@Setter
@Slf4j
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {


    @Autowired
    private UserSecurityService userSecurityService;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager,
                                   UserSecurityService userSecurityService) {
        super(authenticationManager);
        this.userSecurityService = userSecurityService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader(KEY_TOKEN);

        if (StringUtils.isNotBlank(header)) {
            try {
                UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (ExpiredJwtException e) {
                responseJson(response, ErrorCode.ERROR_CODE_TOKEN_EXPIRES, "authentication过期,请重新获取");
                return;
            } catch (Exception e) {
                responseJson(response, ErrorCode.ERROR_CODE_TOKEN_INVALID, "authentication无效");
                return;
            }
        }
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            Result<?> res = Result.failed(e);
            if (e instanceof AppException) {
                log.error("exception : {}", res.getMessage());
            } else {
                log.error("exception : {}", e);
            }
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(JSONObject.toJSONString(res));
            response.flushBuffer();
        }

    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(KEY_TOKEN);
        if (token != null) {
            // parse the token.
            String userName = Jwts.parser().setSigningKey(Constants.CONFIG_JWT_SIGNING_PRIVATE_KEY)
                    .parseClaimsJws(token.replace("Bearer ", Constants.EMPTY)).getBody()
                    .getSubject();
            if (userName != null) {

                return new UsernamePasswordAuthenticationToken(userName,

                        null,
                        // 这里的用户角色应该是从jwt的token中解析出来的,我这边没在jwt中去存角色,所以在这里手写一个区代替,有什么问题可以加我vx: java_ing
                          AuthorityUtils.createAuthorityList("管理员") );
            }
            log.error("token can not be null !");
            return null;
        }
        return null;
    }

    private void responseJson(HttpServletResponse response, ErrorCode errorCode,
                              String errorMessage) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Result<Object> result = Result.failed(errorCode, errorMessage, null);
        response.getWriter().append(JSONObject.toJSONString(result));
        response.flushBuffer();
    }

}

  • JWT的解析和创建代码 AuthenticationUtil

public class AuthenticationUtil {

    public static String parseAuthentication(String signKey, String authorization) {
        return Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(authorization.replace(REQUEST_HEAD_PREFIX, EMPTY))
                .getBody()
                .getSubject();
    }

// 这里的是简单的创建一个jwt 只放了一个用户名 如果需要再jwt中放更多东西需要写一个Claims 把想存的信息放在Claims中
    public static String generateAuthentication(String signKey, Date expireDate, String subject) {
        return Jwts.builder()
                .setSubject(subject)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, signKey)
                .compact();
    }
}

	这样其实就已经差不多完成了,但是因为有的项目中配置了swagger的原因,我们需要在swagger中配置一下token相关的东西。这里我也顺便贴
出来给大家用一下。
  • swagger配置类 SwaggerUIConfig

@Configuration
@EnableSwagger2
public class SwaggerUIConfig implements WebMvcConfigurer {
	@Bean
    public Docket api(){
	    

        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        ticketPar.name(Constants.KEY_TOKEN).description("user token 认证")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();
        pars.add(ticketPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.webapp.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars);
    }


    public ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("api接口说明")
                .description("swagger-ui测试")
                .termsOfServiceUrl("http://localhost/swagger-ui.html")
                .version("1.0.0")
                .build();
    }
    
}

	这样其实就已经大公告成了,我简单测试一下。
  1. 未登录的时候访问接口时,返回用户未登录。

在这里插入图片描述

  1. 用户登录,登录成功返回了一个token。
    在这里插入图片描述

  2. 携带token去访问接口,访问成功。
    在这里插入图片描述

  3. 退出登录。
    在这里插入图片描述

	注意一下,我这里的登录登出接口使用的是security内部接口,为了方便测试我写了一个空的接口方便swagger测试,就像下图一样,
其实这个接口在上线的时候完全没有存在的必要的,不懂的可以私信我或者加我vx: java_ing

在这里插入图片描述

至此整个整合内容就结束了,里面用到了一些常量类中的值,可能直接粘过去你们的代码会有问题,仔细斟辨一下,有不会的地方可以加我vx:java_ing一起交流交流哦~

懂的更多,不懂的更多! 一起加油吧!
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值