无法使用 access_token 访问资源:spring boot Oauth2 [英] Unable to access resources with access_token : spring boot Oauth2

查看:48
本文介绍了无法使用 access_token 访问资源:spring boot Oauth2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我现有的应用程序中实现 Oauth2.最初我添加了 spring 安全性,然后尝试添加 oauth2,添加配置后我能够生成 access_token 但通过使用 access_token 我无法访问资源.

>

这是我的代码:

SecurityConfiguration.java

 @Configuration@启用网络安全公共类 SecurityConfiguration 扩展了 WebSecurityConfigurerAdapter {@自动连线私有数据源数据源;@自动连线私有 ClientDetailsS​​ervice clientDetailsS​​ervice;@覆盖公共无效配置(WebSecurity web)抛出异常{web.ignoring().antMatchers("/resources/**");}@自动连线public void configAuthentication(AuthenticationManagerBuilder auth) 抛出异常 {auth.jdbcAuthentication().dataSource(dataSource);}@覆盖公共无效配置(HttpSecurity http)抛出异常{http.authorizeRequests().antMatchers("/", "/patients").permitAll().antMatchers("/oauth/token").permitAll().anyRequest().authenticated().and().httpBasic();http.csrf().disable();}@覆盖公共无效配置(AuthenticationManagerBuilder auth)抛出异常{auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username, password, 1 as enabled from user where username=?").authoritiesByUsernameQuery("select username, authority where username=?");}@覆盖@豆角,扁豆公共 AuthenticationManager authenticationManagerBean() 抛出异常 {返回 super.authenticationManagerBean();}@豆角,扁豆公共 JdbcTokenStore tokenStore() {返回新的 JdbcTokenStore(dataSource);}@豆角,扁豆@自动连线公共 TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();handler.setTokenStore(tokenStore);handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsS​​ervice));handler.setClientDetailsS​​ervice(clientDetailsS​​ervice);返回处理程序;}@豆角,扁豆@自动连线public ApprovalStore ApprovalStore(TokenStore tokenStore) 抛出异常 {TokenApprovalStore store = new TokenApprovalStore();store.setTokenStore(tokenStore);退货商店;}}

SecurityOAuth2Configuration.java

@Configuration@EnableAuthorizationServer@EnableGlobalMethodSecurity(prePostEnabled = true)@Import(SecurityConfiguration.class)公共类 SecurityOAuth2Configuration 扩展 AuthorizationServerConfigurerAdapter {private static String REALM = "CRM_REALM";私有静态最终 int ONE_DAY = 60 * 60 * 24;私有静态最终 int THIRTY_DAYS = 60 * 60 * 24 * 30;@自动连线私人 TokenStore tokenStore;@自动连线私有数据源数据源;@自动连线私有 UserApprovalHandler userApprovalHandler;@自动连线@Qualifier("authenticationManagerBean")私有 AuthenticationManager authenticationManager;@覆盖公共无效配置(AuthorizationServerSecurityConfigurer oauthServer)抛出异常{oauthServer.realm(REALM);}@覆盖公共无效配置(ClientDetailsS​​erviceConfigurer 客户端)抛出异常 {客户端.jdbc(数据源);}@覆盖public void configure(AuthorizationServerEndpointsConfigurer endpoints) 抛出异常 {endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler).authenticationManager(authenticationManager);}}

ResourceServer.java

@Configuration@EnableResourceServer公共类 ResourceServer 扩展 ResourceServerConfigurerAdapter {@覆盖公共无效配置(HttpSecurity http)抛出异常{http.anonymous().disable().requestMatchers().antMatchers("/patients/**").and().authorizeRequests().antMatchers("/patient/**").access("hasRole('USER')").and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());}}

我使用过

但是当我使用相同的访问令牌来获取资源时,它失败了.

我已经为 oauth 添加了所有必需的表.我有什么遗漏吗?

更新:

我删除了 .and().httpBasic(); 和在 WebsecurityConfigurerAdapter 中添加 @Order(3) 并使用 security.oauth2.resource.filter-order = 3

更新属性文件

现在出现错误<代码>{时间戳":1543500350487,状态":403,错误":禁止","message": "访问被拒绝",路径":/患者/1/"}

更新 2

这是我的用户和权限架构:

用户<代码>+--------------+-------+------+-------+---------+--+|领域 |类型 |空 |钥匙 |默认 |额外 |+--------------+-------+------+-------+---------+--+|身份证 |int(6) 无符号 |否 |PRI |空 |自动增量||用户名 |varchar(50) |否 |联合 |空 |||密码 |varchar(100) |否 ||空 ||+--------------+-------+------+-------+---------+--+

当局<代码>+-----------+-----------------+------+-----+---------+---+|领域 |类型 |空 |钥匙 |默认 |额外 |+-----------+-----------------+------+-----+---------+---+|身份证 |int(6) 无符号 |否 |PRI |空 |自动增量||用户名 |varchar(50) |否 |多 |空 |||权威|varchar(50) |否 ||空 ||+-----------+-----------------+------+-----+---------+---+

解决方案

你应该直接在你的 antmatcher 上使用 hasRole 而不是 access() 函数中的字符串.这将正确评估 hasRole 并正确确定用户有权访问所请求的资源.

这将导致 ResourceServer.java 的以下代码:

@Configuration@EnableResourceServer公共类 ResourceServer 扩展 ResourceServerConfigurerAdapter {@覆盖公共无效配置(HttpSecurity http)抛出异常{http.anonymous().disable().requestMatchers().antMatchers("/patients/**").and().authorizeRequests().antMatchers("/patient/**").hasRole('USER').and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());}}

I am trying to implement Oauth2 in my existing application.Initially I have added spring security and then tried to add oauth2, After adding configuration I am able to generate access_token but by using access_token i am not able to access resources.

Here is my code:

SecurityConfiguration.java

    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/patients").permitAll()
                .antMatchers("/oauth/token").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic();
        http.csrf().disable();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username, password, 1 as enabled from user where username=?")
                .authoritiesByUsernameQuery("select username, authority from authorities where username=?");
    }

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

    @Bean
    public JdbcTokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }
}

SecurityOAuth2Configuration.java

@Configuration
@EnableAuthorizationServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Import(SecurityConfiguration.class)
public class SecurityOAuth2Configuration extends AuthorizationServerConfigurerAdapter {
    private static String REALM = "CRM_REALM";
    private static final int ONE_DAY = 60 * 60 * 24;
    private static final int THIRTY_DAYS = 60 * 60 * 24 * 30;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager);
    }
}

ResourceServer.java

@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.anonymous().disable()
                .requestMatchers().antMatchers("/patients/**").and().authorizeRequests()
                .antMatchers("/patient/**").access("hasRole('USER')")
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

}

I have used this tutorial for reference.

I am able to get access token using basic auth credentials.

But when i used the same access token to get resources, it is failing.

I have added all required tables for oauth. Is there anything am i missing?

Update:

I removed .and().httpBasic(); and added @Order(3) in WebsecurityConfigurerAdapter and updated properties file with security.oauth2.resource.filter-order = 3

now getting error as { "timestamp": 1543500350487, "status": 403, "error": "Forbidden", "message": "Access Denied", "path": "/patient/1/" }

Update 2

here is my user and authorities schema:

user +----------+-----------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-----------------+------+-----+---------+----------------+ | id | int(6) unsigned | NO | PRI | NULL | auto_increment | | username | varchar(50) | NO | UNI | NULL | | | password | varchar(100) | NO | | NULL | | +----------+-----------------+------+-----+---------+----------------+

authorities +-----------+-----------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+-----------------+------+-----+---------+----------------+ | id | int(6) unsigned | NO | PRI | NULL | auto_increment | | username | varchar(50) | NO | MUL | NULL | | | authority | varchar(50) | NO | | NULL | | +-----------+-----------------+------+-----+---------+----------------+

解决方案

You should use hasRole directly on your antmatcher instead of a string inside the access() function. This will evaluate the hasRole correctly and correctly determine that the user has access to the requested resource.

This will result in the following code for ResourceServer.java:

@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.anonymous().disable()
                .requestMatchers().antMatchers("/patients/**").and().authorizeRequests()
                .antMatchers("/patient/**").hasRole('USER')
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

}

这篇关于无法使用 access_token 访问资源:spring boot Oauth2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆