【问题标题】:Spring Boot authentication for different types of User针对不同类型用户的 Spring Boot 身份验证
【发布时间】:2020-10-29 22:45:19
【问题描述】:

我是弹簧靴的新手。我想创建一个教师和学生都可以登录的学校管理系统。登录页面后,我正在发送 jwt 令牌。我想知道这里应该采用什么方法进行身份验证。有些 api 应该由教师和学生严格访问。我看到了 WebSecurityConfigurerAdapter,但不确定谁来处理两组不同的用户?

【问题讨论】:

标签: spring spring-boot spring-security spring-data-jpa


【解决方案1】:

为此,您需要使用 Spring Security。首先,您需要创建两个角色TEACHERSTUDENT。然后根据您的要求,您将在configure 函数中提供对控制器方法的访问权限。 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=?");
    }

【讨论】:

  • 我正在构建rest API,我相信这个可能包括JSP?
  • Rest API 也差不多。您要从数据库中检查用户名和密码还是静态用户名和密码?
  • @Rohit 是的,我使用了 JSP。如果您使用 InMemoryUserDetails 然后在 SecurityConfig 类中创建 UserDetailsService bean。
  • 我推荐你观看 Spring Security Course [链接] (youtube.com/watch?v=her_7pa0vrg&t=9131s)。这让您对 Spring Security 有了全面的了解。
猜你喜欢
  • 2017-10-08
  • 2020-12-12
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 2017-04-07
  • 2019-11-22
相关资源
最近更新 更多