简体   繁体   中英

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    |                |
+----------+-------------+------+-----+---------+----------------+

This is my table in mysql. He the role column will be of 2 values only(admin/user). If it is user I need to give access to specific url and also the same applies for the admin.

How to use Spring security and JPA for this?

Example code from internet

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

Similarly I need the urls("/edit/"),("/add/") to be accessed by the admin and the urls("/rate/") to be accessed by user

You need to create a security config class which extends WebSecurityConfigurerAdapter and override its methods.

To achieve role based access to urls antMatchers are used. For the reference I have appended a method which is overrided in the config 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");
    }

For more details refer https://www.baeldung.com/spring-security-expressions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM