微服务鉴权中心之资源服务配置

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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值