A First Look at Spring Security

1. Introduction

Spring Security is a top-level project in the Spring community, and it is also the Security framework officially recommended by Spring Boot. In addition to regular Authentication and Authorization, Spring Security also provides advanced features such as ACLs, LDAP, JAAS, CAS, etc. to meet security requirements in complex scenarios

2. Understanding

1. Starting from AAA

【Chinese name】:Authentication, authorization and billing

【English name】:Authentication, Authorization and Accounting

【Abbreviation】:AAA

2. What is Authentication?

There is no ROLE in the AAA system, ROLE=ONE Special Authority OR Some Related Authorities Group
 2, Role and Authority

Role=A certain person (Principle) with a set of permissions (Authority/Permission) 

Coarse-grained design 1: A role is represented by an Authority,

For example: Authorities={ROLE_ADMIN},

Represents the administrator role Authorities={ROLE_USER}, represents the ordinary user role

Authorities={ROLE_USER, ROLE_ADMIN}, representing dual-identity user roles

Coarse-grained design 2: A role is represented by the Authority that represents the name of the role itself, and the Authority of the corresponding specific authority, for example: Authorities={ROLE_ADMIN, OP_CreateUser, OP_Drop_User, OP_FrozenUser}, which represents the administrator role and has three A specific permission Authorities={ROLE_USER, OP_ChangePassword, OP_List_Reports}, which represents the role of a common user, with two permissions

3、Spring Security Authentication 

 


 

3. Practical use

1. Dependency jar package:

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

 2. Implement basic login

@Configuration
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/admin/**")
		.authenticated()
		.and().formLogin().permitAll();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("**/js/**", "**/css/**", "**/images/**", "**/**/favicon.ico");

	}

}

 3. JDBC login configuration

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import leader.utils.PasswordHash;

@EnableGlobalMethodSecurity(prePostEnabled = true) //Enable global method validation
@Configuration
public class JDBCSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	private DataSource datasource ;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		JdbcTokenRepositoryImpl repository = getTokenRepository() ;
                /*Disable csrf authentication method*/
		http.csrf().disable() ;
                /*Login and logout matching url*/
		//.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                // The op_createuser role is required to access /manager/createuser
                // The manager role is required to access /manager/**
		http.authorizeRequests().antMatchers("/manager/createuser").hasAnyRole("op_createuser")
		.antMatchers("/manager/**").hasAnyRole("manager")
		.and().formLogin().permitAll().and()
                                 /*Let the browser enable remember me, and enable the remember me button on the login page after opening*/
				.rememberMe().tokenRepository( repository ).tokenValiditySeconds(31536000).and()
				.logout().permitAll().and();
	}
	/**Change remember me to jdbc link mode for verification*/
	public JdbcTokenRepositoryImpl getTokenRepository() {
		JdbcTokenRepositoryImpl r = new JdbcTokenRepositoryImpl();
		r.setDataSource(datasource);
		return r;
	}
	@Override
	public void configure(WebSecurity web) throws Exception {
                /*Configuring js css images, etc. does not require login interception*/
		web.ignoring().antMatchers("**/js/**", "**/css/**", "**/images/**", "**/**/favicon.ico");

	}
	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {
                /** Specify the user login method, specify the password encryption method, use PasswordHash encryption here, you can change it to MD5, or PBE method*/
		auth.userDetailsService(jdbcUserDetailsManager()).passwordEncoder(new PasswordEncoder() {
			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
                                /*Verify whether the password is correct, rawPassword is the password entered for login, and encodedPassword is the password saved in the database*/
				return ((String)rawPassword).equals(encodedPassword);
			}
			@Override
			public String encode(CharSequence rawPassword) {
                                 /*Encrypt the registered password*/
				return (String) rawPassword;
			}
		});
	}
        /**Enable jdbc login, you need to create a user table, the table structure is given later*/
	public UserDetailsManager jdbcUserDetailsManager() throws Exception {
		JdbcUserDetailsManager userMan = new JdbcUserDetailsManager();
		userMan.setDataSource(datasource);
		userMan.setRolePrefix("ROLE_");
		return userMan;
	}
}

 4. Create table structure

 

DROP TABLE IF EXISTS  users ;

CREATE TABLE users (
  username VARCHAR(20) NOT NULL,
  PASSWORD VARCHAR(150) NOT NULL,
  enabled TINYINT(1) DEFAULT NULL,
  PRIMARY KEY (username)
) ENGINE=INNODB DEFAULT CHARSET=utf8 ;

DROP TABLE IF EXISTS authorities;
CREATE TABLE authorities (
  id BIGINT(20) NOT NULL AUTO_INCREMENT,
  username VARCHAR(20) NOT NULL,
  authority VARCHAR(50) NOT NULL,
  PRIMARY KEY (id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS persistent_logins ;
CREATE TABLE persistent_logins (
  id INT(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  username VARCHAR(50) DEFAULT '' COMMENT 'username',
  series VARCHAR(50) DEFAULT '' COMMENT 'series',
  token VARCHAR(64) DEFAULT '' COMMENT 'tokenValue',
  last_used DATETIME DEFAULT NULL COMMENT 'last_used',
  KEY id (id),
  KEY series (series)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
-- user leader , password : 123456
INSERT INTO users(username,PASSWORD,enabled)VALUES('leader' , '123456' , 1) ;
INSERT authorities(username,authority)VALUES('admin' , 'admin') ;

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326799369&siteId=291194637