编程知识 cdmana.com

Spring security pit entry (III)

Before, it was simple to verify the permission value based on memory , actually SpringSecurity The official also provides customized jdbc authentication

The official also gave a database table sql Now, based on this set, make a control on permissions , It's different than before , This time I want to use the authentication of role permissions , That means , Now the database does not store permissions , It's a set of roles , Let's have a look , Basic things don't need to be modified , And memory check permissions are almost the same , It's just , There are some specific methods , See the official documents for details , Just tell me how to use it .

We just need to verify the changes based on memory , The permission verification module is OK , The rest doesn't need to be modified

Build permission verification

package com.shaojie.jdbcauthority.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

/**
 * @author: ShaoJie
 * @data: 2020 year 01 month 10 Japan  11:25
 * @Description:  Security configuration 
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     *  Password encryption 
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     *  Inject data source 
     */
    @Autowired
    public DataSource dataSource;

    /**
     *  to grant authorization 
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         *  Address :org.springframework.security.core.userdetails.jdbc.users.ddl
         *
         * create table users(
         *      username varchar_ignorecase(50) not null primary key,
         *      password varchar_ignorecase(500) not null,
         *      enabled boolean not null
         * );
         * create table authorities (
         *      username varchar_ignorecase(50) not null,
         *      authority varchar_ignorecase(50) not null,
         *      constraint fk_authorities_users foreign key(username) references users(username)
         * );
         * create unique index ix_auth_username on authorities (
         *      username,authority
         * );
         *
         *  there  varchar_ignorecase  type  mysql  Does not support   Replace with  varchar  that will do 
         *
         * create table users(
         *      username varchar(50) not null primary key,
         *      password varchar(500) not null,
         *      enabled boolean not null
         * );
         * create table authorities (
         *      username varchar(50) not null,
         *      authority varchar(50) not null,
         *      constraint fk_authorities_users foreign key(username) references users(username)
         * );
         * create unique index ix_auth_username on authorities (
         *      username,authority
         * );
         */
       //  be based on  JDBC  Validation of the 
        auth.jdbcAuthentication()
                //  Set the prefix of the user role 
//                 .rolePrefix("ROLE_")
                //  Add user 
                // .withUser(new Users())
                //  Inject data source 
                .dataSource(dataSource)
                //  Set the query used to find users by user name 
                .usersByUsernameQuery("select username,password,enabled from users WHERE username=?")
                //  Set up a query to find the user's permissions by user name 
                .authoritiesByUsernameQuery("select username,authority from authorities where username=?")
                //  Password encryption 
                .passwordEncoder(passwordEncoder());

    }

    /**
     *  verification 
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //  The authorization request 
//                .authorizeRequests()
                // antMatchers  Set blocked requests   hasRole  Corresponding role name 
                // .hasAnyAuthority("PRODUCT_ADD")  The permissions of the user 
                .antMatchers("/product/add").hasRole("USER")
                .antMatchers("/product/update").hasRole("ADMIN")
                .antMatchers("/product/list").hasRole("USER")
                .antMatchers("/product/delete").hasRole("ADMIN")
                //  access()  Allows you to specify a protected by any expression URL  similar  antMatchers("/user/**").access("hasRole('USER') and hasRole('DBA')")
                // permitAll  All permissions can access 
                .antMatchers("/login").permitAll()
//                .antMatchers("/**")
                // fullyAuthenticated  Anonymous users are not allowed to view 
//                .fullyAuthenticated()
                //  Set that all requests must be authenticated to access 
                .anyRequest().authenticated()
                .and()
                // httpbasic  Sign in 
                // .httpBasic();
                //  Form login 
                .formLogin()
                //   Log in to the requested page 
                .loginPage("/login")
                //  Handling login requests   Address 
                .loginProcessingUrl("/index")
                //  modify  spring  Provided   Default login parameters 
                .usernameParameter("userName")
                .passwordParameter("password")
                .and()
                //  Turn on remember me 
                .rememberMe()
                .and()
                //  Enable logout 
                .logout()
                .and()
                //  Disable cross domain protection 
                .csrf().disable();
    }
}

Here's what's interesting , there password The encrypted ciphertext is stored , If you save a clear code , Verification will remind , The coded password doesn't look like BCrypt

Therefore, when registering permissions, it is necessary to encrypt through coding , Of course jdbc authentication It also provides a lot of methods , Don't explain in detail , You need to consult the information yourself , To SpringSecurity Into the pit ( 3、 ... and ) until , There are no basic three kinds of permission verification , Detailed in-depth , Still studying , Come here , understand SpringSecurity It's over . Let's make progress together !

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Shao Jie]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/08/20210809183600832b.html

Scroll to Top