开发一个 RESTful 接口的过程中,权限认证是必不可少的一个重要功能。
这里我们以 Spring Boot Security 为例,实现一个自定义的 Token 认证。
大致流程如下:
- 用户 -> 登录页面 -> 用户中心 -> 获取token
- 用户 -> token-> 当前应用 -> token-> 用户中心 -> 认证
首先我们新建配置文件 SecurityConfig。
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public TokenAuthenticationFilter tokenAuthenticationFilterBean() throws Exception { return new TokenAuthenticationFilter(); } @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated(); http.csrf().disable(); http.addFilterBefore(tokenAuthenticationFilterBean(), UsernamePasswordAuthenticationFilter.class); } }
然后实现 TokenAuthenticationFilter 拦截器。
public class TokenAuthenticationFilter extends OncePerRequestFilter { @Autowired private UserService userService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //extract token from header final String token = request.getHeader("x-auth-token"); if (null != token) { //get and check whether token is valid ( from DB or file wherever you are storing the token) final User user = userService.getTokenUser(token); if (null != user) { //Populate SecurityContextHolder by fetching relevant information using token final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); } } filterChain.doFilter(request, response); } }
最后实现用户中心认证的业务逻辑。
@Service public class UserService { @Autowired private OrderService orderService; public User getTokenUser(String token) { //TODO } }
参考:
https://stackoverflow.com/questions/42354138/spring-security-token-based-authentication
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html
https://www.lefer.cn/posts/55880
507 total views, 1 views today