欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解Springboot2.3集成Spring security 框架(原生集成)

程序员文章站 2022-09-25 15:41:11
0、pom

0、pom

<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
	xsi:schemalocation="http://maven.apache.org/pom/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelversion>4.0.0</modelversion>
	<parent>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-parent</artifactid>
		<version>2.3.0.release</version>
		<relativepath/> <!-- lookup parent from repository -->
	</parent>
	<groupid>com.jack</groupid>
	<artifactid>demo</artifactid>
	<version>0.0.1-snapshot</version>
	<packaging>war</packaging>
	<name>demo</name>
	<description>demo project for spring security</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-security</artifactid>
		</dependency>
		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-web</artifactid>
		</dependency>

		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-tomcat</artifactid>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupid>org.springframework.boot</groupid>
			<artifactid>spring-boot-starter-test</artifactid>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupid>org.junit.vintage</groupid>
					<artifactid>junit-vintage-engine</artifactid>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupid>org.springframework.security</groupid>
			<artifactid>spring-security-test</artifactid>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupid>org.springframework.boot</groupid>
				<artifactid>spring-boot-maven-plugin</artifactid>
			</plugin>
		</plugins>
	</build>

</project>

1、springsecurityconfig(security配置)

// 手动定义用户认证 和 // 关联用户service认证 二者取一

这里测试用的是 手动定义用户认证!!!

package com.jack.demo;

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.web.builders.httpsecurity;
import org.springframework.security.config.annotation.web.builders.websecurity;
import org.springframework.security.config.annotation.web.configuration.enablewebsecurity;
import org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter;
import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;

/**
 * @program: demo
 * @description: security 配置
 * @author: jack.fang
 * @date:2020-06-01 1541
 **/

@configuration
@enablewebsecurity
public class springsecurityconfig extends websecurityconfigureradapter {

  @autowired
  private myuserservice myuserservice;

  @override
  protected void configure(authenticationmanagerbuilder auth) throws exception {
    // 手动定义用户认证
    auth.inmemoryauthentication().passwordencoder(new bcryptpasswordencoder()).withuser("admin").password(new bcryptpasswordencoder().encode("123456")).roles("admin");
    auth.inmemoryauthentication().passwordencoder(new bcryptpasswordencoder()).withuser("jack").password(new bcryptpasswordencoder().encode("fang")).roles("user");

    // 关联用户service认证
    //auth.userdetailsservice(myuserservice).passwordencoder(new mypasswordencoder());

    // 默认jdbc认证
    // auth.jdbcauthentication().usersbyusernamequery("").authoritiesbyusernamequery("").passwordencoder(new mypasswordencoder());
  }

  @override
  protected void configure(httpsecurity http) throws exception {
    http.authorizerequests()
        .antmatchers("/").permitall()
        .anyrequest().authenticated()
        .and()
        .logout().permitall()
        .and()
        .formlogin();
    http.csrf().disable();
  }

  @override
  public void configure(websecurity web) throws exception {
    web.ignoring().antmatchers("/js/**","/css/**","/image/**");
  }
}

2、mypasswordencoder(自定义密码比较)

package com.jack.demo;

import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;
import org.springframework.security.crypto.password.passwordencoder;

/**
 * @program: demo
 * @description: 密码加密
 * @author: jack.fang
 * @date:2020-06-01 1619
 **/
public class mypasswordencoder implements passwordencoder {

  @override
  public string encode(charsequence charsequence) {
    return new bcryptpasswordencoder().encode(charsequence.tostring());
  }

  @override
  public boolean matches(charsequence charsequence, string s) {
    return new bcryptpasswordencoder().matches(charsequence,s);
  }
}

3、myuserservice(自行实现的用户登录接口)

具体内容 省略。这里测试用的是springsecurityconfig手动添加用户名与密码。

package com.jack.demo;

import org.springframework.security.core.userdetails.userdetails;
import org.springframework.security.core.userdetails.userdetailsservice;
import org.springframework.security.core.userdetails.usernamenotfoundexception;
import org.springframework.stereotype.component;

/**
 * @program: demo
 * @description: 用户
 * @author: jack.fang
 * @date:2020-06-01 1617
 **/
@component
public class myuserservice implements userdetailsservice {

  @override
  public userdetails loaduserbyusername(string s) throws usernamenotfoundexception {
    return null;
  }
}

4、启动类(测试)

demoapplication.java

package com.jack.demo;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.security.access.prepost.postauthorize;
import org.springframework.security.access.prepost.postfilter;
import org.springframework.security.access.prepost.preauthorize;
import org.springframework.security.access.prepost.prefilter;
import org.springframework.security.config.annotation.method.configuration.enableglobalmethodsecurity;
import org.springframework.security.core.userdetails.user;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

import java.util.list;

@enableglobalmethodsecurity(prepostenabled = true)
@restcontroller
@springbootapplication
public class demoapplication {

	public static void main(string[] args) {
		springapplication.run(demoapplication.class, args);
	}

	@requestmapping("/")
	public string index(){
		return "hello spring security!";
	}

	@requestmapping("/hello")
	public string hello(){
		return "hello !";
	}

	@preauthorize("hasrole('role_admin')")
	@requestmapping("/roleadmin")
	public string role() {
		return "admin auth";
	}


	@preauthorize("#id<10 and principal.username.equals(#username) and #user.username.equals('abc')")
	@postauthorize("returnobject%2==0")
	@requestmapping("/test")
	public integer test(integer id, string username, user user) {
		// ...
		return id;
	}

	@prefilter("filterobject%2==0")
	@postfilter("filterobject%4==0")
	@requestmapping("/test2")
	public list<integer> test2(list<integer> idlist) {
		// ...
		return idlist;
	}
}

测试hello接口(http://localhost:8080/hello)

未登录跳转登录页

详解Springboot2.3集成Spring security 框架(原生集成)

登录springsecurityconfig配置的admin账号与密码123456
成功调用hello

详解Springboot2.3集成Spring security 框架(原生集成)

测试roleadmin(登录admin 123456成功,登录jack fang访问则失败)

详解Springboot2.3集成Spring security 框架(原生集成)

详解Springboot2.3集成Spring security 框架(原生集成)

登出 logout

详解Springboot2.3集成Spring security 框架(原生集成)

到此这篇关于详解springboot2.3集成spring security 框架(原生集成)的文章就介绍到这了,更多相关springboot2.3集成spring security 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!