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

网友投稿 443 2022-11-27


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

0、pom

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

spring-boot-starter-parent

2.3.0.RELEASE

com.jack

demo

0.0.1-SNAPSHOT

war

demo

Demo project for Spring Security

1.8

org.springframework.boot

spring-boot-starter-security

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-tomcat

provided

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.springframework.security

spring-security-test

test

org.springframework.boot

spring-boot-maven-plugin

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

spring-boot-starter-parent

2.3.0.RELEASE

com.jack

demo

0.0.1-SNAPSHOT

war

demo

Demo project for Spring Security

1.8

org.springframework.boot

spring-boot-starter-security

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-tomcat

provided

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.springframework.security

spring-security-test

test

org.springframework.boot

spring-boot-maven-plugin

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 BCryptPasswordEnchttp://oder()).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());

}

@OverrideQYJKMiJh

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 test2(List idList) {

// ...

return idList;

}

}

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

未登录跳转登录页

登录SpringSecurityConfig配置的admin账号与密码123456

成功调用hello

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

登出 logout


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot2.3集成ELK7.1.0的示例代码
下一篇:SpringBoot2.3整合redis缓存自定义序列化的实现
相关文章

 发表评论

暂时没有评论,来抢沙发吧~