簡體   English   中英

Authentication using Spring Boot using Mysql, Spring Data JPA and Spring Security

[英]Authentication using Spring Boot using Mysql, Spring Data JPA and Spring Security

mysql> describe User;

+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| u_id     | int         | NO   | PRI | NULL    | auto_increment |
| email    | varchar(30) | NO   | UNI | NULL    |                |
| name     | varchar(50) | NO   |     | NULL    |                |
| password | varchar(64) | NO   |     | NULL    |                |
| dob      | varchar(30) | YES  |     | NULL    |                |
| role     | varchar(10) | NO   |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

這是我在 mysql 中的表。 他的角色列將只有 2 個值(管理員/用戶)。 如果是用戶,我需要授予對特定 url 的訪問權限,並且同樣適用於管理員。

如何為此使用 Spring 安全性和 JPA?

來自互聯網的示例代碼

http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/users/**").hasRole("USER");

同樣,我需要管理員訪問 urls("/edit/"),("/add/") 和用戶訪問 urls("/rate/")

您需要創建一個擴展 WebSecurityConfigurerAdapter 並覆蓋其方法的安全配置 class。

為了實現對 url 的基於角色的訪問,使用了 antMatchers。 作為參考,我附加了一個在配置 class 中被覆蓋的方法。

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/profile/**").hasAuthority("ROLE_USER")
            .antMatchers("/dashboard/**").hasAuthority("ROLE_ADMIN")
            .and()
            .formLogin()
                .loginPage("/login")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .successHandler(customSuccessHandler)
                    .permitAll()
                    .and()
                .logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/login?logout")
                    .permitAll()
                    .and()
                .exceptionHandling().accessDeniedPage("/403.html");
    }

有關詳細信息,請參閱https://www.baeldung.com/spring-security-expressions

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM