要实现Angular 9 + Spring Boot REST API的社交登录OAUTH2,您可以按照以下步骤进行操作:
angularx-social-login库,该库提供了与社交登录API的集成。import { Component } from '@angular/core';
import { SocialAuthService, GoogleLoginProvider, SocialUser } from 'angularx-social-login';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user: SocialUser | null;
constructor(private authService: SocialAuthService) {}
signInWithGoogle(): void {
this.authService.signIn(GoogleLoginProvider.PROVIDER_ID).then(user => {
this.user = user;
// Send the user details to your Spring Boot REST API
});
}
signOut(): void {
this.authService.signOut().then(() => {
this.user = null;
});
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/login/**", "/oauth2/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.loginPage("/login")
.defaultSuccessUrl("/success")
.failureUrl("/error")
.and()
.logout()
.logoutSuccessUrl("/login")
.and()
.csrf().disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER");
}
}
@RestController注解。import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OAuth2Controller {
@PostMapping("/success")
public void handleSocialLoginSuccess(@RequestBody SocialUser user) {
// Handle social login success here
}
}
请注意,上述代码仅为示例代码,您需要根据实际需求进行修改和适配。此外,您还需要在Spring Boot项目中配置OAuth2客户端详细信息,例如Google客户端ID和秘钥等。
希望以上解决方案能帮助到您!