java - 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)
});
解决方案
推荐阅读
- mongodb - 更新 mongodb 中的嵌套数组元素
- python - 如何在python中显示当前月份的前6个月数据
- javascript - D3 中的 parseTime 和函数有错误
- android - Lottie 动画根本没有显示
- mysql - 实体框架选择单个子类别
- python - Python - 获取适用于 Web 应用程序的 Python3.8 新功能 PYTHONPYCACHEPREFIX
- mongodb - 从子对象 Mongodb 中仅检索所需的元素
- c - 我有一个链表,我想删除重复值
- c++ - 交叉依赖类的问题
- python - 为什么当我设置谷歌浏览器配置文件时 selenium 崩溃?