我有一个SpringBootOAuth2项目,试图将它与angular结合起来。项目代码位于https://github.com/gpdotsingh/idea/tree/master.
分店是主人
后端是位于服务器文件夹中的spring引导
前端在idea文件夹中,该文件夹是有Angular 的
从angular调用下面的回调url时遇到问题,当我试图从前端调用它时,它没有提供访问令牌,该前端是localhost:4200,响应为http://localhost:8086/login;jsessionid=b66be0e6982dd95e8e36ba32d2a1655c?错误
但是当我从localhost:8086调用相同的代码时,它会将我重定向到spring security的登录页面,并进一步给出正确的响应。
回拨url为:http://localhost:8086/login/oauth2/code/cognito1?code=“+code+”&状态=”+我的项目的状态代码为:
@Configuration
@EnableWebSecurity
public class WebConfigurer extends WebSecurityConfigurerAdapter {
private final ObjectMapper mapper;
@Autowired
private JwtRequestFilter jwtRequestFilter;
public WebConfigurer(ObjectMapper mapper) {
this.mapper = mapper;
}
//Add cors , as spring security is getting used
//hence the cors need to be declared here as well else with application.properties it won't work**
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors()
.and()
.authorizeRequests()
.antMatchers("/oauth2/**", "/login**")
.permitAll()
.anyRequest()
.authenticated()
.and()
//.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//.and()
.oauth2Login()
.successHandler(this::successHandler)
.defaultSuccessUrl("/",true)
;
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
private void successHandler(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
OAuth2AuthenticationToken oauthToken =
(OAuth2AuthenticationToken) authentication;
System.out.println("oauthToken:::" + oauthToken);
response.getWriter().write(
mapper.writeValueAsString(Collections.singletonMap("token", authentication.getAuthorities()))
);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
我的客户端配置的类是
@Configuration
public class OAuth2LoginConfig {
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return new InMemoryClientRegistrationRepository(this.clientRegistration());
}
private ClientRegistration[] clientRegistration() {
ClientRegistration [] crArray = new ClientRegistration[2];
ClientRegistration cr1 =
ClientRegistration.withRegistrationId("cognito2")
.clientName("app-client1")
.clientId("xxxxxxxxxxxx")
.clientSecret("xxxxxxxxxxxxxxxxxxxx")
.scope(new String[]{"openid"})
.authorizationUri("https://xxxxxxx.auth.us-east-2.amazoncognito.com/oauth2/authorize")
.tokenUri("https://xxxxxxx.auth.us-east-2.amazoncognito.com/oauth2/token")
.userInfoUri("https://xxxxxxx.auth.us-east-2.amazoncognito.com/oauth2/userInfo")
.jwkSetUri("https://cognito-idp.us-east-2.amazonaws.com/us-east-xxxxxxx/.well-known/jwks.json")
.clientName("app-client")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("http://localhost:4200/callback")
.build();
ClientRegistration cr2 =
ClientRegistration.withRegistrationId("cognito1")
.clientName("app-client2")
.clientId("xxxxxxxxx")
.clientSecret("xxxxxxxxxxx")
.scope(new String[]{"openid"})
.authorizationUri("https://xxxxxxx.auth.us-east-2.amazoncognito.com/oauth2/authorize")
.tokenUri("https://xxxxxx.auth.us-east-2.amazoncognito.com/oauth2/token")
.userInfoUri("https://xxxxxxxx.auth.us-east-2.amazoncognito.com/oauth2/userInfo")
.jwkSetUri("https://cognito-idp.us-east-2.amazonaws.com/us-east-2_72ZHiqEHa/.well-known/jwks.json")
.clientName("app-client2")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("http://localhost:4200/callback")
.build();
crArray[0] = cr1;
crArray[1] = cr2;
return crArray;
}
}
Angular 回调组件的代码是
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SecurityServiceService } from 'src/app/services/security-service.service';
@Component({
selector: 'app-callback',
templateUrl: './callback.component.html',
styleUrls: ['./callback.component.css']
})
export class CallbackComponent implements OnInit {
constructor(private route:ActivatedRoute
, private router : Router
, private securityService: SecurityServiceService) { }
ngOnInit(): void {
this.route.queryParams.subscribe(p=>{
console.log("code and state "+p);
this.securityService.fetchToken(p.code,p.state) // Not able to call fetch data
.subscribe(data=>{
console.log("tokes "+data);
this.securityService.updateToken(data.token);
this.router.navigate(["/home"]);
})
})
}
}
服务代码是
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SecurityServiceService {
private url ="https://xxxxxxxx.auth.us-east-2.amazoncognito.com/login?response_type=code&client_id=xxxxxxxxx&scope=openid&state=xxxxxxxxx%3D&redirect_uri=http://localhost:4200/callback&nonce=NJJQy8vKDEVbZ533VQWanAneNojgg4aTeKlh6_E1x1Y";
private tokenKey ='token';
constructor(private http:HttpClient) { }
login()
{
window.open(this.url,'_self');
}
getToken()
{
return localStorage.getItem(this.tokenKey);
}
fetchToken(code:string,state:string): Observable<any>
{
state = encodeURIComponent(state);
code = encodeURIComponent(code);
console.log("State is "+ state+ " code "+code);
return this.http.get('http://localhost:8086/login/oauth2/code/cognito1?code='+code+'&state='+state);
}
updateToken(token: string)
{
localStorage.setItem(this.tokenKey,token);
}
isLoggedIn(): boolean
{
const token = this.getToken();
return token!=null;
}
}
暂无答案!
目前还没有任何答案,快来回答吧!