security 认证流程
分为两个部分,认证和鉴权
当一个请求到来时,我们需要观察其是否是已经认证的用户,主要是查看浏览器的cookie和remerber me 数据库。如果不是认证用户转到登录,这时候我们就进入了登录的逻辑里。
如果是认证用户,我们就进入鉴权的逻辑。
具体的逻辑我们可以看下图
说起JWT,我们应该来谈一谈基于token的认证和传统的session认证的区别。
什么是 JWT — JSON WEB TOKEN
传统的session认证
我们知道,http协议本身是一种无状态的协议,而这就意味着如果用户向我们的应用提供了用户名和密码来进行用户认证,那么下一次请求时,用户还要再一次进行用户认证才行,因为根据http协议,我们并不能知道是哪个用户发出的请求,所以为了让我们的应用能识别是哪个用户发出的请求,我们只能在服务器存储一份用户登录的信息,这份登录信息会在响应时传递给浏览器,告诉其保存为cookie,以便下次请求时发送给我们的应用,这样我们的应用就能识别请求来自哪个用户了,这就是传统的基于session认证。
但是这种基于session的认证使应用本身很难得到扩展,随着不同客户端用户的增加,独立的服务器已无法承载更多的用户,而这时候基于session认证应用的问题就会暴露出来.
基于token的鉴权机制
基于token的鉴权机制类似于http协议也是无状态的,它不需要在服务端去保留用户的认证信息或者会话信息。这就意味着基于token认证机制的应用不需要去考虑用户在哪一台服务器登录了,这就为应用的扩展提供了便利。
流程上是这样的:
- 用户使用用户名密码来请求服务器
- 服务器进行验证用户的信息
- 服务器通过验证发送给用户一个token
- 客户端存储token,并在每次请求时附送上这个token值
- 服务端验证token值,并返回数据
这个token必须要在每次请求时传递给服务端,它应该保存在请求头里, 另外,服务端要支持CORS(跨来源资源共享)策略,一般我们在服务端这么做就可以了Access-Control-Allow-Origin: *。
实现
因为secrity他的默认是基于session和cooki只上的,所以我们需要对其的一些逻辑进行更改。
取消csrf的防护(crsf是基于cookie的攻击,所以可以关掉防护)
.csrf().disable()
关掉session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
@Overrideprotected void configure(HttpSecurity http) throws Exception {/*AccessDecisionManager accessDecisionManager = (AccessDecisionManager) ioc.getBean("dynamicAccessDecisionManager");*/http.authorizeRequests().antMatchers(excludeUrls).permitAll().antMatchers("/admin/**").hasRole("admin").antMatchers("/user/**").hasRole("user").anyRequest().authenticated().and().csrf().disable() // 禁用 Spring Security 自带的跨域处理.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().addFilterAfter(new JwtFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);// 定制我们自己的 session 策略:调整为让 Spring Security 不创建和使用 session;//.accessDecisionManager(accessDecisionManager) //根据voter配置动态权限}
具体更改流程
jwt只需要对其认证原理进行更改,每一次带token的链接,我们都需要为其加上一个认证的authentication,并且验证这个authentication。
得到authenication
验证authenication
代码
pom
<dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.4.0</version></dependency><!-->序列化<--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.79</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency>
token util
package com.example.springbootsecurityjwtdemo.security;import com.alibaba.fastjson.JSON;import com.auth0.jwt.JWT;import com.auth0.jwt.JWTVerifier;import com.auth0.jwt.algorithms.Algorithm;import com.auth0.jwt.interfaces.Claim;import com.auth0.jwt.interfaces.DecodedJWT;import org.springframework.security.core.GrantedAuthority;import org.springframework.stereotype.Component;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;public class TokenUtil {// 过期时间是七天private static final long EXPIRE_TIME= 60*60*24*7;private static final String ISSER = "auth0";private static final String TOKEN_SECRET="token123"; //密钥盐public final static JWTVerifier VERIFIER = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer(ISSER).build();/*** 签名生成* @return*/public static String sign(String name, List<String> roles){String token = null;try {Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);token = JWT.create().withIssuer(ISSER).withClaim("username", name).withClaim("roles", JSON.toJSONString(roles)).withExpiresAt(expiresAt)// 使用了HMAC256加密算法。.sign(Algorithm.HMAC256(TOKEN_SECRET));} catch (Exception e){e.printStackTrace();}return token;}/*** 签名验证* @param token* @return*/public static boolean verify(String token){try {VERIFIER.verify(token);return true;} catch (Exception e){return false;}}/*** 得到token存的值* @param token* @return*/public static Map<String,Claim> getClaimsFromToken(String token){try {DecodedJWT jwt = VERIFIER.verify(token);return jwt.getClaims();} catch (Exception e){return null;}}}
过滤器
import com.alibaba.fastjson.JSON;import com.auth0.jwt.interfaces.Claim;import com.example.springbootsecurityjwtdemo.exception.BusinessException;import com.example.springbootsecurityjwtdemo.result.ResponseMag;import org.springframework.security.access.SecurityConfig;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Map;public class JwtFilter extends BasicAuthenticationFilter {public JwtFilter(AuthenticationManager authenticationManager) {super(authenticationManager);}@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {String token = request.getHeader("token");System.out.println(token);if(token==null|| "".equals(token)){chain.doFilter(request, response);return;}Map<String, Claim> claimMap = TokenUtil.getClaimsFromToken(token);if(claimMap==null){changeToExectionController(request,response, new BusinessException(ResponseMag.TokenError));}String username = claimMap.get("username").asString();List<String> roles = JSON.parseArray(claimMap.get("roles").asString(),String.class);List<GrantedAuthority> authorities = new ArrayList<>();for(String s:roles){authorities.add(()->s);}System.out.println(claimMap.get("roles").asString());UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username,null,authorities);SecurityContextHolder.getContext().setAuthentication(authentication);getAuthenticationManager().authenticate(authentication);chain.doFilter(request, response);}private void changeToExectionController(HttpServletRequest request, HttpServletResponse response,Exception e) throws ServletException, IOException {// 异常捕获、发送到UnsupportedJwtExceptionrequest.setAttribute("Exception", e);// 将异常分发到UnsupportedJwtException控制器request.getRequestDispatcher("/Exception").forward(request, response);}}
provider
package com.example.springbootsecurityjwtdemo.security;import java.util.ArrayList;import org.springframework.security.authentication.AuthenticationProvider;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;public class CustomAuthenticationProvider implements AuthenticationProvider {@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {System.out.println("hello");return authentication;}@Overridepublic boolean supports(Class<?> aClass) {return true;}}
配置类
package com.example.springbootsecurityjwtdemo.security;import com.example.springbootsecurityjwtdemo.mapper.RolePermissionMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.access.AccessDecisionManager;import org.springframework.security.access.AccessDecisionVoter;import org.springframework.security.access.ConfigAttribute;import org.springframework.security.access.hierarchicalroles.RoleHierarchy;import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;import org.springframework.security.authentication.AuthenticationManager;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.builders.WebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;import javax.sql.DataSource;@Configurationpublic class MySecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredUserServiceImpl userServiceImpl;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.authenticationProvider(new CustomAuthenticationProvider());}@AutowiredApplicationContext ioc;public final String[] excludeUrls = {"/Exception","/login","/register","/doLogin","/test/hello","/swagger**/**","/webjars/**","/v3/**"};@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/js/**", "/css/**","/images/**");web.securityInterceptor((FilterSecurityInterceptor) ioc.getBean("filterSecurityInterceptor"));}@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Overrideprotected void configure(HttpSecurity http) throws Exception {/*AccessDecisionManager accessDecisionManager = (AccessDecisionManager) ioc.getBean("dynamicAccessDecisionManager");*/http.authorizeRequests().antMatchers(excludeUrls).permitAll().antMatchers("/admin/**").hasRole("admin").antMatchers("/user/**").hasRole("user").anyRequest().authenticated().and().csrf().disable() // 禁用 Spring Security 自带的跨域处理.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().addFilterAfter(new JwtFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);// 定制我们自己的 session 策略:调整为让 Spring Security 不创建和使用 session;//.accessDecisionManager(accessDecisionManager) //根据voter配置动态权限}@BeanRoleHierarchy roleHierarchy() {RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();hierarchy.setHierarchy("ROLE_admin > ROLE_user");return hierarchy;}}
