OAuth2.0 - 微服务认证方案
微服务方案:
网关作用:
本身使用OAuth2.0 做权限防护,然后对于后端服务做粗粒度Scope鉴权,所有鉴权通过后,将令牌进行解密,并自定义内容格式和加密方式传递给后台。
@Configuration public class ResouceServerConfig { public static final String RESOURCE_ID = "res1"; //uaa资源服务配置 @Configuration @EnableResourceServer public class UAAServerConfig extends ResourceServerConfigurerAdapter { @Autowired private TokenStore tokenStore; @Override public void configure(ResourceServerSecurityConfigurer resources){ resources.tokenStore(tokenStore).resourceId(RESOURCE_ID) .stateless(true); } @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/uaa/**").permitAll(); } } //order资源 //uaa资源服务配置 @Configuration @EnableResourceServer public class OrderServerConfig extends ResourceServerConfigurerAdapter { @Autowired private TokenStore tokenStore; @Override public void configure(ResourceServerSecurityConfigurer resources){ resources.tokenStore(tokenStore).resourceId(RESOURCE_ID) .stateless(true); } @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/order/**").access("#oauth2.hasScope('ROLE_API')"); } } //配置其它的资源服务.. }
token再次加工:
public class AuthFilter extends ZuulFilter { @Override public boolean shouldFilter() { return true; } @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); //从安全上下文中拿 到用户身份对象 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if(!(authentication instanceof OAuth2Authentication)){ return null; } OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication; Authentication userAuthentication = oAuth2Authentication.getUserAuthentication(); //取出用户身份信息 String principal = userAuthentication.getName(); //取出用户权限 List<String> authorities = new ArrayList<>(); //从userAuthentication取出权限,放在authorities userAuthentication.getAuthorities().stream().forEach(c->authorities.add(((GrantedAuthority) c).getAuthority())); OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request(); Map<String, String> requestParameters = oAuth2Request.getRequestParameters(); Map<String,Object> jsonToken = new HashMap<>(requestParameters); if(userAuthentication!=null){ jsonToken.put("principal",principal); jsonToken.put("authorities",authorities); } //把身份信息和权限信息放在json中,加入http的header中,转发给微服务 ctx.addZuulRequestHeader("json-token", EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonToken))); return null; }
。。
posted on 2021-11-03 16:47 TrustNature 阅读(242) 评论(0) 编辑 收藏 举报