【问题标题】:spring-oauth2: HTTP Status 403 - Access Deniedspring-oauth2:HTTP 状态 403 - 拒绝访问
【发布时间】:2015-12-05 22:07:24
【问题描述】:

我尝试使用 curl 和 spring security oauth2 向我的 rest-api 发送请求,但我收到此错误:

* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /test/oauth/token HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:8080
> Accept: application/json
> Authorization: Basic bXktdHJ1c3RlZC1jbGllbnQ6MTIzNDU=
> Content-Length: 99
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 99 out of 99 bytes
< HTTP/1.1 403 Forbidden
* Server Apache-Coyote/1.1 is not blacklisted
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: text/html;charset=utf-8
< Content-Language: en
< Content-Length: 1030
< Date: Wed, 09 Sep 2015 19:37:49 GMT
< 
<!DOCTYPE html><html><head><title>Apache Tomcat/8.0.20 - Error report</title><style type="text/css">H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}.line {height: 1px; background-color: #525D76; border: none;}</style> </head><body><h1>HTTP Status 403 - Access Denied</h1><div class="line"></div><p><b>type</b> Status report</p><p><b>message</b> <u>Access Denied</u></p><p><b>description</b> <u>Access to the specified resource has been forbidden.</u></p><hr class="line"><h3>Apache Tomcat/8.0.20</h3></body><* Connection #0 to host localhost left intact

我的要求:

curl -X GET -k -vu my-trusted-client:12345 http://localhost:8080/test/oauth/token -H "Accept: application/jd "grant_type=password&scope=read&client_secret=12345&client_id=my-trusted-client&resource_id=rest_api"

我的代码的一部分:

我的 oauth2server 配置:

@Configuration
@EnableResourceServer
public class OAuth2ServerConfiguration {

    @Configuration
    @EnableAuthorizationServer
    protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private AuthenticationManager authenticationManager;

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

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients.inMemory()
                .withClient("my-trusted-client")
                    .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                    .authorities("USER")
                    .scopes("read", "write", "trust")
                    .resourceIds("rest_api")
                    .secret("12345")
                    .accessTokenValiditySeconds(600);
            // @formatter:on
        }
    }
}

我的安全配置类:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        //builder.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

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

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security.authorizeRequests()
            .antMatchers("/oauth/token")
            .hasRole("USER")
            .antMatchers("/greeting").authenticated();
    }
}

我的控制器:

@Path("/oauth")
@Produces(MediaType.APPLICATION_JSON)
public class TestController {

    public TestController() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(OAuth2ServerConfiguration.class);
        AutowireCapableBeanFactory acbFactory = applicationContext.getAutowireCapableBeanFactory();
        acbFactory.autowireBean(this);
    }

    @GET
    @Path("/token")
    public Response testToken() {

        return Response.status(200).entity("is working \n").build();
    }
}

Spring 已经生成了 refresh_token,但我没有得到 access_token 有人可以帮助我吗?什么是假的?我的代码还是我的请求?

谢谢。

【问题讨论】:

    标签: java spring rest curl spring-security


    【解决方案1】:

    您正在使用grant_type=password 参数,表示您要使用资源所有者流。

         +----------+
         | Resource |
         |  Owner   |
         |          |
         +----------+
              v
              |    Resource Owner
             (A) Password Credentials
              |
              v
         +---------+                                  +---------------+
         |         |>--(B)---- Resource Owner ------->|               |
         |         |         Password Credentials     | Authorization |
         | Client  |                                  |     Server    |
         |         |<--(C)---- Access Token ---------<|               |
         |         |    (w/ Optional Refresh Token)   |               |
         +---------+                                  +---------------+
    
                Figure 5: Resource Owner Password Credentials Flow
    
       The flow illustrated in Figure 5 includes the following steps:
    
       (A)  The resource owner provides the client with its username and
            password.
    
       (B)  The client requests an access token from the authorization
            server's token endpoint by including the credentials received
            from the resource owner.  When making the request, the client
            authenticates with the authorization server.
    
       (C)  The authorization server authenticates the client and validates
            the resource owner credentials, and if valid, issues an access
            token.
    

    您必须包含此流程的用户名和密码,而不仅仅是您的 client_id 和 client_secret。

    从代码中您没有为用户设置身份验证管理器。尝试将其添加到您的 SecurityConfiguration 课程中。

    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
    {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
    

    测试一下

    curl -X GET -k -vu user:password http://localhost:8080/test/oauth/token -H "Accept: application/jd "grant_type=password&scope=read&client_secret=12345&client_id=my-trusted-client"
    

    【讨论】:

    • 它不起作用。我犯了同样的错误。我在 securityConfiguration 中添加了部分代码并测试了您的请求。但什么都没有:-(
    • 我添加了这部分代码 security.authorizeRequests() .antMatchers(HttpMethod.GET, "/oauth/token") .hasRole("USER") .and().httpBasic().realmName (“OAuth 服务器”);到我的 HttpSecurity,我得到了请求的响应,但没有 access_token。知道为什么吗?
    • 你能用curl的POST方法测试它吗,最新版本的spring-security-oauth似乎只允许POST方法进行身份验证。
    • 我尝试使用 post 并在没有 access_token 的情况下得到我的回复。一部分代码:@POST @Path("/token") @Produces(MediaType.APPLICATION_JSON) public Response testToken(String me) { return Response.status(200).entity(me + "is working fine \n") 。建造(); } 和响应 {"me": "emo"}&grant_type=password&scope=read&client_secret=12345&client_id=clientsecretis 工作正常
    • 当我在参数中输入错误密码时,我会收到相同的响应。正常吗?类似于: curl ...-d "username=US&password=PASS&grant_type=password"
    猜你喜欢
    • 2020-01-25
    • 2018-07-19
    • 2015-12-03
    • 1970-01-01
    • 2021-12-13
    • 2019-11-06
    • 2020-12-19
    • 2020-04-26
    • 2017-12-20
    相关资源
    最近更新 更多