mall整合SpringSecurity和JWT实现认证和授权(一)

本文主要讲解mall通过整合SpringSecurity和JWT实现后台用户的登录和授权功能,同时改造Swagger-UI的配置使其可以自动记住登录令牌进行发送。

项目使用框架介绍

SpringSecurity

SpringSecurity是一个强大的可高度定制的认证和授权框架,对于Spring应用来说它是一套Web安全标准。SpringSecurity注重于为Java应用提供认证和授权功能,像所有的Spring项目一样,它对自定义需求具有强大的扩展性。

JWT

JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。

JWT的组成

JWT token的格式:header.payload.signature

header中用于存放签名的生成算法

{"alg": "HS512"}Copy to clipboardErrorCopied

payload中用于存放用户名、token的生成时间和过期时间

{"sub":"admin","created":1489079981393,"exp":1489684781}Copy to clipboardErrorCopied

signature为以header和payload生成的签名,一旦header和payload被篡改,验证将失败

//secret为加密算法的密钥Stringsignature=HMACSHA512(base64UrlEncode(header)+"."+base64UrlEncode(payload),secret)Copy to clipboardErrorCopied

JWT实例

这是一个JWT的字符串

eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE1NTY3NzkxMjUzMDksImV4cCI6MTU1NzM4MzkyNX0.d-iki0193X0bBOETf2UN3r3PotNIEAV7mzIxxeI5IxFyzzkOZxS0PGfF_SK6wxCv2K8S0cZjMkv6b5bCqc0VBwCopy to clipboardErrorCopied

可以在该网站上获得解析结果:https://jwt.io/ 

mall整合SpringSecurity和JWT实现认证和授权(一)_第1张图片

JWT实现认证和授权的原理

用户调用登录接口,登录成功后获取到JWT的token;

之后用户每次调用接口都在http的header中添加一个叫Authorization的头,值为JWT的token;

后台程序通过对Authorization头中信息的解码及数字签名校验来获取其中的用户信息,从而实现认证和授权。

Hutool

Hutool是一个丰富的Java开源工具包,它帮助我们简化每一行代码,减少每一个方法,mall项目采用了此工具包。

项目使用表说明

ums_admin:后台用户表

ums_role:后台用户角色表

ums_permission:后台用户权限表

ums_admin_role_relation:后台用户和角色关系表,用户与角色是多对多关系

ums_role_permission_relation:后台用户角色和权限关系表,角色与权限是多对多关系

ums_admin_permission_relation:后台用户和权限关系表(除角色中定义的权限以外的加减权限),加权限是指用户比角色多出的权限,减权限是指用户比角色少的权限

整合SpringSecurity及JWT

在pom.xml中添加项目依赖

org.springframework.bootspring-boot-starter-securitycn.hutoolhutool-all4.5.7io.jsonwebtokenjjwt0.9.0Copy to clipboardErrorCopied

添加JWT token的工具类

用于生成和解析JWT token的工具类

相关方法说明:

generateToken(UserDetails userDetails) :用于根据登录用户信息生成token

getUserNameFromToken(String token):从token中获取登录用户的信息

validateToken(String token, UserDetails userDetails):判断token是否还有效

packagecom.macro.mall.tiny.common.utils;importio.jsonwebtoken.Claims;importio.jsonwebtoken.Jwts;importio.jsonwebtoken.SignatureAlgorithm;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.security.core.userdetails.UserDetails;importorg.springframework.stereotype.Component;importjava.util.Date;importjava.util.HashMap;importjava.util.Map;/**

* JwtToken生成的工具类

* Created by macro on 2018/4/26.

*/@ComponentpublicclassJwtTokenUtil{privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(JwtTokenUtil.class);privatestaticfinalStringCLAIM_KEY_USERNAME="sub";privatestaticfinalStringCLAIM_KEY_CREATED="created";@Value("${jwt.secret}")privateStringsecret;@Value("${jwt.expiration}")privateLongexpiration;/**

    * 根据负责生成JWT的token

    */privateStringgenerateToken(Mapclaims){returnJwts.builder().setClaims(claims).setExpiration(generateExpirationDate()).signWith(SignatureAlgorithm.HS512,secret).compact();}/**

    * 从token中获取JWT中的负载

    */privateClaimsgetClaimsFromToken(Stringtoken){Claimsclaims=null;try{claims=Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();}catch(Exceptione){LOGGER.info("JWT格式验证失败:{}",token);}returnclaims;}/**

    * 生成token的过期时间

    */privateDategenerateExpirationDate(){returnnewDate(System.currentTimeMillis()+expiration*1000);}/**

    * 从token中获取登录用户名

    */publicStringgetUserNameFromToken(Stringtoken){Stringusername;try{Claimsclaims=getClaimsFromToken(token);username=claims.getSubject();}catch(Exceptione){username=null;}returnusername;}/**

    * 验证token是否还有效

    *

    * @param token      客户端传入的token

    * @param userDetails 从数据库中查询出来的用户信息

    */publicbooleanvalidateToken(Stringtoken,UserDetailsuserDetails){Stringusername=getUserNameFromToken(token);returnusername.equals(userDetails.getUsername())&&!isTokenExpired(token);}/**

    * 判断token是否已经失效

    */privatebooleanisTokenExpired(Stringtoken){DateexpiredDate=getExpiredDateFromToken(token);returnexpiredDate.before(newDate());}/**

    * 从token中获取过期时间

    */privateDategetExpiredDateFromToken(Stringtoken){Claimsclaims=getClaimsFromToken(token);returnclaims.getExpiration();}/**

    * 根据用户信息生成token

    */publicStringgenerateToken(UserDetailsuserDetails){Mapclaims=newHashMap<>();claims.put(CLAIM_KEY_USERNAME,userDetails.getUsername());claims.put(CLAIM_KEY_CREATED,newDate());returngenerateToken(claims);}/**

    * 判断token是否可以被刷新

    */publicbooleancanRefresh(Stringtoken){return!isTokenExpired(token);}/**

    * 刷新token

    */publicStringrefreshToken(Stringtoken){Claimsclaims=getClaimsFromToken(token);claims.put(CLAIM_KEY_CREATED,newDate());returngenerateToken(claims);}}Copy to clipboardErrorCopied

添加SpringSecurity的配置类

packagecom.macro.mall.tiny.config;importcom.macro.mall.tiny.component.JwtAuthenticationTokenFilter;importcom.macro.mall.tiny.component.RestAuthenticationEntryPoint;importcom.macro.mall.tiny.component.RestfulAccessDeniedHandler;importcom.macro.mall.tiny.dto.AdminUserDetails;importcom.macro.mall.tiny.mbg.model.UmsAdmin;importcom.macro.mall.tiny.mbg.model.UmsPermission;importcom.macro.mall.tiny.service.UmsAdminService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.http.HttpMethod;importorg.springframework.security.authentication.AuthenticationManager;importorg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;importorg.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.annotation.web.configuration.EnableWebSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;importorg.springframework.security.config.http.SessionCreationPolicy;importorg.springframework.security.core.userdetails.UserDetailsService;importorg.springframework.security.core.userdetails.UsernameNotFoundException;importorg.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;importorg.springframework.security.crypto.password.PasswordEncoder;importorg.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;importjava.util.List;/**

* SpringSecurity的配置

* Created by macro on 2018/4/26.

*/@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled=true)publicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@AutowiredprivateUmsAdminServiceadminService;@AutowiredprivateRestfulAccessDeniedHandlerrestfulAccessDeniedHandler;@AutowiredprivateRestAuthenticationEntryPointrestAuthenticationEntryPoint;@Overrideprotectedvoidconfigure(HttpSecurityhttpSecurity)throwsException{httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf.disable().sessionManagement()// 基于token,所以不需要session.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers(HttpMethod.GET,// 允许对于网站静态资源的无授权访问"/","/*.html","/favicon.ico","/**/*.html","/**/*.css","/**/*.js","/swagger-resources/**","/v2/api-docs/**").permitAll().antMatchers("/admin/login","/admin/register")// 对登录注册要允许匿名访问.permitAll().antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求.permitAll()//.antMatchers("/**")//测试时全部运行访问//.permitAll().anyRequest()//除上面外的所有请求全部需要鉴权认证.authenticated();//禁用缓存        httpSecurity.headers().cacheControl();//添加JWT filter        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(),UsernamePasswordAuthenticationFilter.class);//添加自定义未授权和未登录结果返回        httpSecurity.exceptionHandling().accessDeniedHandler(restfulAccessDeniedHandler).authenticationEntryPoint(restAuthenticationEntryPoint);}@Overrideprotectedvoidconfigure(AuthenticationManagerBuilderauth)throwsException{auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());}@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}@BeanpublicUserDetailsServiceuserDetailsService(){//获取登录用户信息returnusername->{UmsAdminadmin=adminService.getAdminByUsername(username);if(admin!=null){ListpermissionList=adminService.getPermissionList(admin.getId());returnnewAdminUserDetails(admin,permissionList);}thrownewUsernameNotFoundException("用户名或密码错误");};}@BeanpublicJwtAuthenticationTokenFilterjwtAuthenticationTokenFilter(){returnnewJwtAuthenticationTokenFilter();}@Bean@OverridepublicAuthenticationManagerauthenticationManagerBean()throwsException{returnsuper.authenticationManagerBean();}}Copy to clipboardErrorCopied

相关依赖及方法说明

configure(HttpSecurity httpSecurity):用于配置需要拦截的url路径、jwt过滤器及出异常后的处理器;

configure(AuthenticationManagerBuilder auth):用于配置UserDetailsService及PasswordEncoder;

RestfulAccessDeniedHandler:当用户没有访问权限时的处理器,用于返回JSON格式的处理结果;

RestAuthenticationEntryPoint:当未登录或token失效时,返回JSON格式的结果;

UserDetailsService:SpringSecurity定义的核心接口,用于根据用户名获取用户信息,需要自行实现;

UserDetails:SpringSecurity定义用于封装用户信息的类(主要是用户信息和权限),需要自行实现;

PasswordEncoder:SpringSecurity定义的用于对密码进行编码及比对的接口,目前使用的是BCryptPasswordEncoder;

JwtAuthenticationTokenFilter:在用户名和密码校验前添加的过滤器,如果有jwt的token,会自行根据token信息进行登录。

添加RestfulAccessDeniedHandler

packagecom.macro.mall.tiny.component;importcn.hutool.json.JSONUtil;importcom.macro.mall.tiny.common.api.CommonResult;importorg.springframework.security.access.AccessDeniedException;importorg.springframework.security.web.access.AccessDeniedHandler;importorg.springframework.stereotype.Component;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/**

* 当访问接口没有权限时,自定义的返回结果

* Created by macro on 2018/4/26.

*/@ComponentpublicclassRestfulAccessDeniedHandlerimplementsAccessDeniedHandler{@Overridepublicvoidhandle(HttpServletRequestrequest,HttpServletResponseresponse,AccessDeniedExceptione)throwsIOException,ServletException{response.setCharacterEncoding("UTF-8");response.setContentType("application/json");response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));response.getWriter().flush();}}Copy to clipboardErrorCopied

添加RestAuthenticationEntryPoint

packagecom.macro.mall.tiny.component;importcn.hutool.json.JSONUtil;importcom.macro.mall.tiny.common.api.CommonResult;importorg.springframework.security.core.AuthenticationException;importorg.springframework.security.web.AuthenticationEntryPoint;importorg.springframework.stereotype.Component;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/**

* 当未登录或者token失效访问接口时,自定义的返回结果

* Created by macro on 2018/5/14.

*/@ComponentpublicclassRestAuthenticationEntryPointimplementsAuthenticationEntryPoint{@Overridepublicvoidcommence(HttpServletRequestrequest,HttpServletResponseresponse,AuthenticationExceptionauthException)throwsIOException,ServletException{response.setCharacterEncoding("UTF-8");response.setContentType("application/json");response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));response.getWriter().flush();}}Copy to clipboardErrorCopied

添加AdminUserDetails

packagecom.macro.mall.tiny.dto;importcom.macro.mall.tiny.mbg.model.UmsAdmin;importcom.macro.mall.tiny.mbg.model.UmsPermission;importorg.springframework.security.core.GrantedAuthority;importorg.springframework.security.core.authority.SimpleGrantedAuthority;importorg.springframework.security.core.userdetails.UserDetails;importjava.util.Collection;importjava.util.List;importjava.util.stream.Collectors;/**

* SpringSecurity需要的用户详情

* Created by macro on 2018/4/26.

*/publicclassAdminUserDetailsimplementsUserDetails{privateUmsAdminumsAdmin;privateListpermissionList;publicAdminUserDetails(UmsAdminumsAdmin,ListpermissionList){this.umsAdmin=umsAdmin;this.permissionList=permissionList;}@OverridepublicCollectiongetAuthorities(){//返回当前用户的权限returnpermissionList.stream().filter(permission->permission.getValue()!=null).map(permission->newSimpleGrantedAuthority(permission.getValue())).collect(Collectors.toList());}@OverridepublicStringgetPassword(){returnumsAdmin.getPassword();}@OverridepublicStringgetUsername(){returnumsAdmin.getUsername();}@OverridepublicbooleanisAccountNonExpired(){returntrue;}@OverridepublicbooleanisAccountNonLocked(){returntrue;}@OverridepublicbooleanisCredentialsNonExpired(){returntrue;}@OverridepublicbooleanisEnabled(){returnumsAdmin.getStatus().equals(1);}}Copy to clipboardErrorCopied

添加JwtAuthenticationTokenFilter

在用户名和密码校验前添加的过滤器,如果请求中有jwt的token且有效,会取出token中的用户名,然后调用SpringSecurity的API进行登录操作。

packagecom.macro.mall.tiny.component;

import com.macro.mall.tiny.common.utils.JwtTokenUtil;

import org.slf4j.Logger;importorg.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;importjava.io.IOException;/**

* JWT登录授权过滤器

* Created by macro on 2018/4/26.

*/publicclassJwtAuthenticationTokenFilterextendsOncePerRequestFilter{privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);@AutowiredprivateUserDetailsServiceuserDetailsService;@AutowiredprivateJwtTokenUtiljwtTokenUtil;@Value("${jwt.tokenHeader}")privateStringtokenHeader;@Value("${jwt.tokenHead}")privateStringtokenHead;@OverrideprotectedvoiddoFilterInternal(HttpServletRequestrequest,HttpServletResponseresponse,FilterChainchain)throwsServletException,IOException{StringauthHeader=request.getHeader(this.tokenHeader);if(authHeader!=null&&authHeader.startsWith(this.tokenHead)){StringauthToken=authHeader.substring(this.tokenHead.length());// The part after "Bearer "Stringusername=jwtTokenUtil.getUserNameFromToken(authToken);LOGGER.info("checking username:{}",username);if(username!=null&&SecurityContextHolder.getContext().getAuthentication()==null){UserDetailsuserDetails=this.userDetailsService.loadUserByUsername(username);if(jwtTokenUtil.validateToken(authToken,userDetails)){UsernamePasswordAuthenticationTokenauthentication=newUsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());authentication.setDetails(newWebAuthenticationDetailsSource().buildDetails(request));LOGGER.info("authenticated user:{}",username);SecurityContextHolder.getContext().setAuthentication(authentication);}}}chain.doFilter(request,response);}}

你可能感兴趣的:(mall整合SpringSecurity和JWT实现认证和授权(一))