1.资源服务配置
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {
@Resource(name = "redisTokenStore")
private TokenStore tokenStore;
private static final String RESOURCE_ID = "res1";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID)
.tokenStore(tokenStore)
.stateless(true)
.accessDeniedHandler(new CustomAccessDeniedHandler());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").permitAll()
.and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
2.Token及权限拦截校验(此处非必须,如果认为微服务之间相互信任可不校验)
@Component
public class AuthenticationFilter extends OncePerRequestFilter {
@Autowired
private TokenStore tokenStore;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String requestUrl = request.getRequestURI();
AntPathMatcher pathMatcher = new AntPathMatcher();
// 通过role接口配置权限
if (!pathMatcher.match("/api/student/grade", requestUrl)) {
filterChain.doFilter(request, response);
return;
}
String tokenStr = request.getHeader("IPC-TOKEN");
String token = tokenStr.split(" ")[1];
if (StringUtils.isBlank(token)) {
throw new ServletException();
}
String principal = "";
String authorities = "";
try {
OAuth2Authentication authentication = tokenStore.readAuthentication(token);
Object prinipal = authentication.getPrincipal();
String json = JSON.toJSONString(prinipal);
principal = JSON.parseObject(json).getString("username");
} catch (Exception e) {
e.printStackTrace();
}
// 根据username获取role及权限
// Role role = roleService.getById(user.getDefaultRoleId());
// authorities = role.getPermissions();
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
principal, null,
AuthorityUtils.createAuthorityList(authorities));
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
filterChain.doFilter(request, response);
}
}