当前位置: 首页 > 知识库问答 >
问题:

Spring oauth2基本身份验证

吕永嘉
2023-03-14

我正在尝试使用OAuth2实现开发一个带有Spring Security性的rest api。但是如何删除基本身份验证呢。我只想向body发送用户名和密码,并在postman上获取令牌。

@Configuration
public class OAuthServerConfigration {

private static final String SERVER_RESOURCE_ID = "oauth2-server";

private static InMemoryTokenStore tokenStore = new InMemoryTokenStore();


@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(SERVER_RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
         http.anonymous().disable().requestMatchers().antMatchers("/api/**").and().authorizeRequests().antMatchers("/api/**").access("#oauth2.hasScope('read')");
    }
}

@Configuration
@EnableAuthorizationServer
protected static class AuthConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;


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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("client")
            .secret("$2a$10$5OkeCLKNs/BkdO0qcYRri.MdIcKhFvElAllhPgLfRQqG7wkEiPmq2")
                .authorizedGrantTypes("password","authorization_code","refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
              .scopes("read", "write", "trust")
                .resourceIds(SERVER_RESOURCE_ID)
                  //.accessTokenValiditySeconds(ONE_DAY)
                  .accessTokenValiditySeconds(300)
                  .refreshTokenValiditySeconds(50);

    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {

        oauthServer
                // we're allowing access to the token only for clients with 'ROLE_TRUSTED_CLIENT' authority
                .tokenKeyAccess("hasAuthority('ROLE_TRUSTED_CLIENT')")
                .checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");

    }

 }

}

@Configuration
@Order(2)
public static class ApiLoginConfig extends 
WebSecurityConfigurerAdapter{   
    @Autowired
    DataSource dataSource;

    @Autowired
    ClientDetailsService clientDetailsService;


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

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.httpBasic().disable().csrf().disable().antMatcher("/oauth/token").authorizeRequests().anyRequest().permitAll();


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

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

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

要删除基本身份验证,并从邮递员的get token中发送body标记中的用户名密码吗

我遇到了一些问题{"错误":"未经授权","error_description":"没有客户端身份验证。尝试添加适当的身份验证过滤器。"}

共有1个答案

申屠喜
2023-03-14

在方法的@EnableAuthorizationServer配置类中:-

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)

尝试添加以下内容:-

oauthServer.allowFormAuthenticationForClients()

完成后,您必须调用oauth get token url,如下所示:-

URL将与http相同://{HOST_NAME}/oauth/token

HTTP方法类型现在将是POST

标题:-

Content-Type=application/x-www-form-urlencoded

参数将是邮递员正文中x-www-form-urlencoded中的键值对

对于客户端\u凭据授予\u类型:-

grant_type=client_credentials
client_id=client_id_value
client_secret=client_secret_value
scope=scopes

对于密码授予类型:-

grant_type=password
client_id=client_id_value
client_secret=client_secret_value
scope=scopes
username=username
password=password

范围将在此处用逗号分隔

 类似资料:
  • 问题内容: 从HttpClient 4.3开始,我一直在使用HttpClientBuilder。我正在连接到具有基本身份验证的REST服务。我将凭据设置如下: 但是,这不起作用(我正在使用的REST服务返回401)。怎么了? 问题答案: 从此处的 抢先身份验证 文档中: http://hc.apache.org/httpcomponents-client- ga/tutorial/html/aut

  • 目前我正在开发一个Java工具,它应该可以更新Confluence服务器页面。使用Curl一切都像一个符咒,但是当使用Postman或Java代码(HttpClient Java11)时,我得到了一个 HTTP状态401–未经授权 反应。 在下面的语句中使用curl curl--basic-u user:password-X PUT-H“内容类型:application/json”-d“@test

  • 几天没有任何进展,我需要你的帮助。 使用GWT,我试图与REST服务器通信,服务器位于不同的URL上(需要CORS)<我的配置:服务器spring boot 1.3.3 客户端-GWT 1.7-restygwt 2.0.3 当我在Spring中禁用安全性时,我可以在我的GWT客户端中获取数据。 但是当我启用它时,我总是收到401个请求。REST URL请求直接在Web浏览器中工作(带有其身份验证对

  • 我尝试了angular.js,并从一个restful api的web-ui开始(使用超文本传输协议基本授权)。这真的很好,除了授权工作。 到目前为止,我使用的是设置密码,但大多数情况下浏览器会打开http basic auth的默认登录表单。另一个奇怪的行为是angular请求不包含授权头(选项和GET请求都不包含)。我还尝试使用header配置在每个请求上设置此header,但这也不起作用。 有

  • 我有一个基本的SOAP服务endpoint,实际上是SAP ECC,它表示一个服务。我已经使用SOAPUI4.5测试了该服务,使用HTTPAuth可以正常工作,可以根据事物的外观进行抢占。我看到一个出站“Authorization:Basic BASE64”,服务会做出相应响应。 我现在正试图将其引入Java。我想我会采取SAAJ方法: 但我无法在中添加HTTP身份验证。我相信SAAJ提供了控制S

  • 但我对spring-boot/java还是个新手...有谁能帮我把这条路走对吗? 多谢了。