让Spring Security 来保护你的Spring Boot项目吧

扩展WebSecurityConfigurerAdapter类

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

//身份验证管理生成器

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

}

//HTTP请求安全处理

@Override

protected void configure(HttpSecurity http) throws Exception {

}

//WEB安全

@Override

public void configure(WebSecurity web) throws Exception {

}

学习一门新知识的最好的方法就是看源码,按住ctrl 移动鼠标到WebSecurityConfigurerAdapter点击查看源码。

我们首先介绍

//身份验证管理生成器

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

}

的重写。

选择查询用户详细信息的服务

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

//1.启用内存用户存储

// auth.inMemoryAuthentication()

// .withUser(“xfy”).password(passwordEncoder().encode(“1234”)).roles(“ADMIN”).and()

// .withUser(“tom”).password(passwordEncoder().encode(“1234”)).roles(“USER”);

//2.基于数据库表进行验证

// auth.jdbcAuthentication().dataSource(dataSource)

// .usersByUsernameQuery(“select username,password,enabled from user where username = ?”)

// .authoritiesByUsernameQuery(“select username,rolename from role where username=?”)

// .passwordEncoder(passwordEncoder());

//3.配置自定义的用户服务

auth.userDetailsService(myUserDetailService);

}

启用内存用户处理和基于数据库表验证都要完全依赖于框架本身的验证逻辑。本人推荐第三种配置自定义的用户服务。

实现security官方的UserDetailsService

源码:

package org.springframework.security.core.userdetails;

public interface UserDetailsService {

UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;

}

自己创建实现类

import com.young.security.mysecurity.pojo.Role;

import com.young.security.mysecurity.pojo.User;

import com.young.security.mysecurity.repository.RoleRepository;

import com.young.security.mysecurity.repository.UserRepository;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.AuthorityUtils;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.stereotype.Component;

import java.util.ArrayList;

import java.util.List;

/**

  • Create by stefan

  • Date on 2018-05-17 22:49

  • Convertion over Configuration!

*/

@Component

@Slf4j

public class MyUserDetailService implements UserDetailsService {

@Autowired

private PasswordEncoder passwordEncoder;

@Autowired

UserRepository userRepository;

@Autowired

private RoleRepository roleRepository;

@Override

public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

User user = userRepository.findByUsername(name);

if (user==null){

throw new AuthenticationCredentialsNotFoundException(“authError”);

}

log.info(“{}”,user);

List role = roleRepository.findByUsername(name);

log.info(“{}”,role);

List authorities = new ArrayList<>();

role.forEach(role1 -> authorities.addAll(AuthorityUtils.commaSeparatedStringToAuthorityList(“ROLE_”+role1.getRolename())));

log.info(“{}”,authorities);

return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);

}

}

任何关于数据库的业务这里不做解释。详情请看源码。

需要注意的是 Security默认使用了密码加密保护,我们配置密码转换器申明使用什么加密方式。这里推荐BCryptPassword,同样是5.0的推荐。

在刚才配置类SecurityConfig中配置

@Bean

public static PasswordEncoder passwordEncoder() {

return new BCryptPasswordEncoder();

}

查看源码encode()这个方法是加密,matches()是判断加密密码与输入框明文密码是否一致。

拦截请求

接下来,我们看看

@Override

protected void configure(HttpSecurity http){

super.configure(http);

}

默认配置是

protected void configure(HttpSecurity http) throws Exception {

http

.authorizeRequests()

.anyRequest().authenticated()

.and()

.formLogin()

.and()

.httpBasic();

}

自己修改后的配置

@Override

protected void configure(HttpSecurity http) throws Exception {

http.formLogin().loginPage(“/signIn”).loginProcessingUrl(“/user/userLogin”)

.and()

.logout().logoutUrl(“/logout”)

.and()

.authorizeRequests()

.antMatchers(“/signIn”,“/hello”).permitAll()

.antMatchers(“/index”).authenticated()

.antMatchers(“/admin/**”,“/add”).hasRole(“ADMIN”)

.regexMatchers(“/admin1/.*”).access(“hasRole(‘ADMIN’) or hasRole(‘ADMIN1’)”)

.anyRequest().authenticated()

.and()

.requiresChannel().antMatchers(“/add”).requiresSecure()//https://127.0.0.1:8443/add

.and()

.rememberMe().tokenValiditySeconds(2419200).tokenRepository(persistentTokenRepository());

}

spring security 的拦截语法

我们首先调用authorizeRequests(),然后调用该方法所返回的对象的方法来配置请求级别的安全性细节。

antMatchers的使用(Ant风格的通配符):

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip1024b (备注Java)
img

最后总结

ActiveMQ+Kafka+RabbitMQ学习笔记PDF

image.png

  • RabbitMQ实战指南

image.png

  • 手写RocketMQ笔记

image.png

  • 手写“Kafka笔记”

image

关于分布式,限流+缓存+缓存,这三大技术(包含:ZooKeeper+Nginx+MongoDB+memcached+Redis+ActiveMQ+Kafka+RabbitMQ)等等。这些相关的面试也好,还有手写以及学习的笔记PDF,都是啃透分布式技术必不可少的宝藏。以上的每一个专题每一个小分类都有相关的介绍,并且小编也已经将其整理成PDF啦

一个人可以走的很快,但一群人才能走的更远。如果你从事以下工作或对以下感兴趣,欢迎戳这里加入程序员的圈子,让我们一起学习成长!

AI人工智能、Android移动开发、AIGC大模型、C C#、Go语言、Java、Linux运维、云计算、MySQL、PMP、网络安全、Python爬虫、UE5、UI设计、Unity3D、Web前端开发、产品经理、车载开发、大数据、鸿蒙、计算机网络、嵌入式物联网、软件测试、数据结构与算法、音视频开发、Flutter、IOS开发、PHP开发、.NET、安卓逆向、云计算

tiveMQ+Kafka+RabbitMQ)等等。这些相关的面试也好,还有手写以及学习的笔记PDF,都是啃透分布式技术必不可少的宝藏。以上的每一个专题每一个小分类都有相关的介绍,并且小编也已经将其整理成PDF啦

一个人可以走的很快,但一群人才能走的更远。如果你从事以下工作或对以下感兴趣,欢迎戳这里加入程序员的圈子,让我们一起学习成长!

AI人工智能、Android移动开发、AIGC大模型、C C#、Go语言、Java、Linux运维、云计算、MySQL、PMP、网络安全、Python爬虫、UE5、UI设计、Unity3D、Web前端开发、产品经理、车载开发、大数据、鸿蒙、计算机网络、嵌入式物联网、软件测试、数据结构与算法、音视频开发、Flutter、IOS开发、PHP开发、.NET、安卓逆向、云计算

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值