spring security和spring oauth结合后 spring security配置不管用了
    spring security
@Configuration
@EnableResourceServer
public class AppWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    private ZuulProperties zuulProperties;
    @Autowired
    private AuthenticationSuccessHandler appAuthenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler appAuthenticationFailureHandler;
    @Autowired
    private AccessDeniedHandler appAccessDeniedHandler;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager manager = super.authenticationManagerBean();
        return manager;
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers(HttpMethod.GET,zuulProperties.getAuth().toGetAdapter())
            .permitAll()
            .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST,zuulProperties.getAuth().toPostAdapter())
                .permitAll()
            .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
            .and()
                .exceptionHandling().accessDeniedHandler(appAccessDeniedHandler)
            .and()
                .csrf().disable();
    }

spring oauth相关

 @Configuration
@EnableAuthorizationServer
public class AppAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private final AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private ZuulProperties zuulProperties;
    @Autowired
    private TokenStore tokenStore ;
    @Autowired(required = false)
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Autowired(required = false)
    private TokenEnhancer jwtTokenEnhancer;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public AppAuthorizationServerConfig(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        OAuth2ClientProperties[] clientProperties = zuulProperties.getOauth().getClients();
        if(ArrayUtils.isNotEmpty(zuulProperties.getOauth().getClients())) {
            for (OAuth2ClientProperties oAuth2ClientProperties : clientProperties) {
                 builder.withClient(oAuth2ClientProperties.getClientId())
                   .secret(oAuth2ClientProperties.getClientSecret())
                   //token有效时间
                   .accessTokenValiditySeconds(oAuth2ClientProperties.getAccessTokenValiditySeconds())
                   //验证模式
                   .authorizedGrantTypes("password","authorization_code","client_credentials","implicit","refresh_token")
                   //刷新时间
                   .refreshTokenValiditySeconds(3600*24*100)
                    //跳转地址
                   .redirectUris("ws.28ph.cn")
                   //权限
                   .scopes("all");
            }
        } 
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .tokenStore(tokenStore)
                .userDetailsService(userDetailsService)
                .reuseRefreshTokens(true);
        if(jwtAccessTokenConverter != null && jwtTokenEnhancer!=null) {
            TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
            List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
            tokenEnhancers.add(jwtTokenEnhancer);
            tokenEnhancers.add(jwtAccessTokenConverter);
            enhancerChain.setTokenEnhancers(tokenEnhancers);
            endpoints
                    .tokenEnhancer(enhancerChain)
                    .accessTokenConverter(jwtAccessTokenConverter);
        }
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .passwordEncoder(passwordEncoder)
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

}

问题的产生:我在spring security配置了几个不需要拦截的uri,但是加入spring oauth 全部被拦截了,如果删掉@EnableResourceServer会出现 发出来的token 认证不了url的问题。。

然后我想大不了不用spring oauth 自带的发token方式。然后我在spring security的成功handler上下发token ,以下是代码

/**
 * 认证成功跳转
 * @author w4837
 *
 */
@Component(value = "AppAuthenticationSuccessHandler")
@Slf4j
public class AppAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired
    private AuthorizationServerTokenServices authorizationServerTokenServices;



    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                    HttpServletResponse httpServletResponse, Authentication authentication)
            throws IOException, ServletException {
        log.info("登陆成功");
        String header = httpServletRequest.getHeader("Authorization");
        //请求头包含Authorization 并且以"Basic "开始
        if (header == null || !header.startsWith("Basic ")) {
            throw new UnapprovedClientAuthenticationException("请求头中无Authorization信息");
        }

        try {
            String[] tokens = extractAndDecodeHeader(header, httpServletRequest);
            assert tokens.length == 2;

            String clientId = tokens[0];
            String clientSecret = tokens[1];
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
            if(clientDetails == null) {
                throw new UnapprovedClientAuthenticationException("clientId:"+clientId+"对应的信息不存在。");
            }else if(!StringUtils.equals(clientSecret, clientDetails.getClientSecret())) {
                throw new UnapprovedClientAuthenticationException("clientId:"+clientId+"对应的信息不匹配。");
            }
            @SuppressWarnings("unchecked")
            TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(),"custom");

            OAuth2Request auth2Request = tokenRequest.createOAuth2Request(clientDetails);

            OAuth2Authentication auth2Authentication = new OAuth2Authentication(auth2Request, authentication);

            OAuth2AccessToken createAccessToken = authorizationServerTokenServices.createAccessToken(auth2Authentication);
            // 判断需要的返回类型
            httpServletResponse.setContentType(ZuulAppConstant.CONTENT_TYPE_JSON);
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(createAccessToken));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 解析header中编码后的数据
     *
     * @param header
     * @param request
     * @return
     * @throws IOException
     */
    private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {

        byte[] base64Token = header.substring(6).getBytes("UTF-8");
        byte[] decoded;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }

        String token = new String(decoded, "UTF-8");

        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        }
        return new String[] { token.substring(0, delim), token.substring(delim + 1) };
    }

结果 启动还是报循环依赖的错误


***************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  appAuthorizationServerConfig defined in file [F:\yulece_aike_ideaword\app-management\app-management-zuul\target\classes\com\yulece\app\management\zuul\authorization\AppAuthorizationServerConfig.class]
↑     ↓
|  appWebSecurityConfigurerAdapter (field private org.springframework.security.web.authentication.AuthenticationSuccessHandler com.yulece.app.management.zuul.authorization.AppWebSecurityConfigurerAdapter.appAuthenticationSuccessHandler)
↑     ↓
|  AppAuthenticationSuccessHandler (field private org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices com.yulece.app.management.zuul.authorization.handler.AppAuthenticationSuccessHandler.defaultAuthorizationServerTokenServices)
↑     ↓
|  org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration (field private java.util.List org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration.configurers)
└─────┘

0
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Spring Security、Spring Social 、Spring Security OAuth
本教程是全网最细致地讲解Spring Security、Spring Social 、Spring Security OAuth三种技术开发安全的REST服务,彻底掌握一线互联网公司主流的身份认证和授权方式。 Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
Spring security oauth源码
从官网下载的oauth2实例sparklr2与tonr2
Spring Security for OAuth
认证提供方如何提供移动终端登陆?rnAuthorizationEndpoint中authorize方法的principal总是为null,应该是没有登陆的原因,不知道principal是怎么个机制,用户完成登陆后如何取到principal
spring security spring security
spring security spring security 中文文档
50 Spring Security、Spring Social 、Spring Security OAuth
教程视频:spring提供的安全权限框架,Spring Security、Spring Social 、Spring Security OAuth
spring security 结合cas配置
spring security 结合cas 单点登录系统 cas客户端的配置文件
spring security的配置和方法
记得有位坛友在回复《学习Acegi-认证(authentication)》[url]http://www.iteye.com/topic/52975[/url]时提到Spring已经集成Acegi认证,先将实例奉上。 1)新建WebProject “MyE_spring_security” 2)加入Spring3.0 core, aop, persistence, web, secur...
spring security的应用和配置
Spring Security 2.0 是Spring框架的下一代安全系统。它在上一代Acegi安全系统上又添加了许多新特性。本文件对Spring Security运行一个简单的应用程序和配置进行详细的说明。
spring security 配置
最近想学一下spring security,在网上查的资料http://old.family168.com/oa/springsecurity/html/ch001-helloworld.html,第一步在xml中配置过滤器就出现错误了rnException starting filter springSecurityFilterChainrnorg.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is definedrn我用的spring2.0,大家有谁配置过指点一下
spring security 使用及配置
spring security 使用及配置
spring security配置实例
spring security配置实例
spring security的配置
NULL 博文链接:https://lihong11.iteye.com/blog/1321007
Spring Security 配置
介绍了Spring Security 的配置方法及其使用技巧
SPRING SECURITY配置
NULL 博文链接:https://lgd-lc.iteye.com/blog/873765
Spring Security 3.2.x 配置
NULL 博文链接:https://panyongzheng.iteye.com/blog/2080390
Spring Security
Spring Security的文档,有点老了,偶然发现在硬盘上,放上来
spring security
这个不错的资源,可以下载来看看哦~!呵呵O(∩_∩)O~
Spring security
spring security 配置文件 博文链接:https://darkstone.iteye.com/blog/194795
Spring security
值得研究,对于菜鸟来说很好的一本资料哦,呵呵!真的哦,看i愿意尝试
Spring Security源码分析十六:Spring Security项目实战
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企
Spring Security 参考手册Spring Security中文版
很多独立软件供应商,因为灵活的身份验证模式二选择Spring Security。这样做允许他们快速的集成到他们的终端客户需求的解决方案而不用进行大量工程或者改变客户的环境。如果上面的验证机制不符合你的需求,Spring Security 是一个开放的平台,要实现你 自己的验证机制检查。 为了阅读方便,自己导出的文档,格式为HTML,文件也相对较小。 文档原地址:https://springcloud.cc/spring-security-zhcn.html