我有一个spring boot应用程序,我有几个REST API。现在我想对所有请求进行授权检查。这涉及使用x509客户端证书的每个请求,然后是一些用于授权目的的业务逻辑,类似于角色检查。 什么是最好的地方,即应该在DispatcherServlet - doDispatch方法中完成此检查?对Controller中的每个请求进行相同的检查没有多大意义。 有人可以建议在弹簧启动应用程序中将这些检查放在哪里吗?
答案 0 :(得分:0)
你有两个选择。 Java配置或xml配置。
我推荐java配置。创建一个配置类并像这样配置
对于java配置,它看起来像
@Configuration
@EnableWebSecurity
public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.inMemoryAuthentication()
.withUser("jduser").password("jdu@123").authorities("ROLE_USER")
.and()
.withUser("jdadmin").password("jda@123").authorities("ROLE_USER","ROLE_ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
.antMatchers("/userPage").access("hasRole('ROLE_USER')")
.antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
.and()
.formLogin().loginPage("/loginPage")
.defaultSuccessUrl("/homePage")
.failureUrl("/loginPage?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/loginPage?logout");
}
}