首页 > 解决方案 > Angular中的OAuth2身份验证Java Spring错误

问题描述

我已经在 java spring 中实现了 oAuth2。当我使用基本身份验证从邮递员发送请求时,我得到令牌作为响应。但是当我从角度发送它时,它返回 401。

请检查随附的代码和图像。

package com.spring.rest.spring_rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter{

    @Autowired
    private AuthenticationManager authenticationManager;

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

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//      super.configure(security);
        security.checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//      super.configure(clients);
        clients.inMemory().withClient("my-trusted-client")
            .authorizedGrantTypes("client_credentials","password")
            .authorities("ROLE_CLIENT","ROLE_TRUSTED_CLIENT")
            .scopes("read","write","trust")
            .resourceIds("oauth2-resource")
            .accessTokenValiditySeconds(5000)
            .secret("secret");
    }

}

在此处输入图像描述

在此处输入图像描述

角度代码:DataService.ts

login(loginPayload) {
    const headers = {
      'Authorization': 'Basic ' + btoa('my-trusted-client:secret'),
      'Content-type': 'application/json'
    }
    return this._http.post('http://localhost:8080/' + 'oauth/token', loginPayload, {headers});
  }

登录.ts

const body = new HttpParams()
      .set('username', this.f.username.value)
      .set('password', this.f.password.value)
      .set('grant_type', 'password');

    this.dataService.login(body.toString()).subscribe(data => {
      window.sessionStorage.setItem('token', JSON.stringify(data));
      console.log(window.sessionStorage.getItem('token'));
      this.router.navigate(['user-profile']);
    }, error => {
        alert(error.error.error_description)
    });

标签: javaangularspringtypescriptoauth-2.0

解决方案


推荐阅读