我正在构建一个Spring Boot应用程序,以便将用户添加到Redmine环境中的组。
为此我使用了buildt-in org.springframework.web.client.RestTemplate。
我是Spring Boot Security的新手,所以我希望以下是正确的。
“标准”Spring Boot Securtity系统的工作原理如下:
首先,您必须定义一个实现 org.springframework.security.core.userdetails.UserDetailsService的类。 这个类只有一个方法可以覆盖UserDetailsService中的'loadUserByUsername(String username)'方法,如下所示:
@Service
public class SecurityServiceImpl implements UserDetailsService {
@Autowired
Service anService;
@Override
public CurrentUser loadUserByUsername(String username) throws UsernameNotFoundException {
CurrentUser currentUser = anService.getCurrentUser(username, password);
if(currentUser != null) {
return currentUser;
} else {
throw new UsernameNotFoundException("User with name " + username + "not found.");
}
}
然后,您必须定义一个扩展 org.springframework.security.core.userdetails.User 的UserClass。在上面的代码示例中,它是'CurrentUser'。 CurrentUser类如下所示:
public class CurrentUser extends org.springframework.security.core.userdetails.User {
public CurrentUser(String login, String password) {
super(login, password, AuthorityUtils.createAuthorityList(Role.ADMIN.toString()));
}
最后一步是说Spring,它必须使用UserDetailsService。这是在扩展 org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter 的类中完成的。 该类看起来像这样:
@Configuration
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Qualifier("securityServiceImpl")
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/overview", true)
.failureUrl("/login?error")
.usernameParameter("loginName")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.rememberMe()
;
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
所以我在这里说Spring,登录页面位于/ login下,如果登录成功,则应该访问/ overview页面。
如果有人想登录登录页面,那么他将数据放入表单中。 Spring知道,该站点是登录页面,并使用指定的 UserDetailsService 来获取用户的数据。为此,它会读取loginName并将其告诉 UserDetailsService 。 Userdetails服务使用 loeadUserbyUsername(String username)方法通过loginName获取用户的数据。 Spring会比较loginName和password,如果它们相同,那么用户可以登录,如果没有,则不能登录。
重点是,我在后台没有数据库,因为它只是一个REST应用程序,应该由Spring Boot Security准备。
所以最好的问题是,我怎么能说Spring,如果用户想登录,Spring会创建一个REST调用(在我的案例中是Redmine)API?返回HTTP状态将说明用户是否可以登录。
有什么想法吗?