我是Spring Boot的新手。我想创建一个学校管理系统,供老师和学生登录。登录Page后,我将发送jwt令牌。我想知道这里应该采用什么方法进行身份验证。有一些api应该由老师和学生严格访问。我看到的是WebSecurityConfigurerAdapter,但不确定谁可以处理两组不同的用户?
答案 0 :(得分:0)
为此,您需要使用Spring Security。首先,您需要创建两个角色TEACHER
和STUDENT
。然后,根据您的要求,您将在configure
函数中访问控制器的方法。 配置功能应位于SecurityConfig.java中。并且@EnableWebSecurity
注释也应该放在类的顶部。如果您从数据库中读取了用户名和密码,则在configAuthentication
函数中将进行检查。
例如
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/").hasAnyRole("STUDENT","TEACHER")
.antMatchers("/add_friends").hasAnyRole( "TEACHER")
.antMatchers("/showAllData").hasAnyRole( "TEACHER")
.antMatchers("/show_users").hasAnyRole( "TEACHER")
.and().formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.successForwardUrl("/welcome_page")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedPage("/accessDenied");
http.csrf().disable();
}
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username,password, enabled from core_users where username=?")
.authoritiesByUsernameQuery("select username, authority from core_authorities where username=?");
}