[英]How to connect angular 9 login page to spring boot app?
我在第一个用户微服务中成功实现了spring security,下面是配置代码:
@EnableWebSecurity
public class MSSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/users/UserById/*")
.antMatchers("/users/Activate/**/");
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
角度服务的完整语法是:
return this.http.get<UserObj>(`http://localhost:9023/users/Authenticate?username=aaa&password=bbb`
用户详情服务:
@Service
public class MSUserDetailsService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
User user = userRepository.getUser(userName);
if (user != null) {
return new MSUserDetails(user);
}
throw new UsernameNotFoundException("Not found: " + userName);
}
}
这是从 angular 处理服务调用的控制器:
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {
@GetMapping("/Authenticate")
public User authenticatie(@RequestParam("username") String username, @RequestParam("password") String password) {
return userService.authenticatie(username, password);
}
我需要知道如何将此身份验证连接到 spring 安全性,以便下次用户发送不同的 url 时,它将已经进行身份验证?
您设置 url 的方式就像弹簧靴也处理应用程序的前端部分一样。 可能您从教程中获得了此代码,如果没问题,但不打算用于与不同前端的集成。
即使应用程序在同一台服务器上运行,端口也可能是一个问题,我不确定您是否可以克服。
你在评论中告诉我你有一个 RestController 来登录,这很好,因为这个想法是朝着正确的解决方案发展的。 此端点必须负责验证用户(最终针对数据库,我看到您目前正在使用静态值)并返回某种令牌以存储在您的角度(例如 jwt)中。
想法如下,角度登录页面必须调用在 spring-boot 中创建为 @RestController 的登录端点并返回某种 ot 令牌。 Angular 保存在 cookie 或本地存储中提供的令牌。 然后 angular 将其用于针对 spring boot 的请求。
然后必须在 websecurity 中配置需要身份验证的 spring boot 端点才能这样做。 阅读如何在 Spring Boot 中创建用于验证的过滤器并实现一个过滤器。
额外注意,可能您还需要允许 cors 从 angular 到 spring boot。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.