Spring Security详细介绍及使用含完整代码(值得珍藏)

org.springframework.boot spring-boot-starter-security io.jsonwebtoken jjwt 0.9.1

4.2 Security配置

然后,创建一个配置类来设置Spring Security:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NioJwtDecoder;

import java.util.Collections;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

// 模拟用户服务,实际开发中应该使用数据库或其他持久化存储
@Bean
@Override
public UserDetailsService userDetailsService() {
// 创建内存中的用户,实际开发中应从数据库或其他存储中获取
User user = User.withUsername(“user”)
.password(passwordEncoder().encode(“password”))
.roles(“USER”)
.build();

return new InMemoryUserDetailsManager(Collections.singletonList(user));
}

@Bean
public PasswordEncoder passwordEncoder() {
// 使用BCrypt进行密码编码
return new BCryptPasswordEncoder();
}

@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}

@Bean
public JwtDecoder jwtDecoder() {
// 这里使用固定的密钥,实际开发中应该使用安全的密钥管理方式
String secret = “mySecret”;
return JwtDecoders.fromSecretKey(secret);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(“/login”).permitAll() // 允许所有用户访问登录端点
.anyRequest().authenticated() // 其他所有请求需要认证
.and()
.addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}

4.3 用户服务

在实际应用中,你可能需要一个用户服务来从数据库中获取用户信息。这里我们创建一个简单的UserService类,但在本示例中不会使用它,因为我们在配置中使用了内存中的用户。

import org.springframework.security.core.userdetails.User;
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.Service;

@Service
public class UserService implements UserDetailsService {

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 在实际应用中,这里应该根据用户名从数据库或其他数据源加载用户
// 假设我们有一个用户名为"user",密码为"password"的用户
if (“user”.equals(username)) {
return new User(“user”, “$2a 10 10 10dXJ3SW6G7P50lGmMkkmwe.20c02F55t218l9.kR6l/.6”,
new ArrayList<>());
} else {
throw new UsernameNotFoundException("User not found with username: " + username);
}
}
}

4.4 创建JWT认证过滤器

这个过滤器会检查HTTP请求头中的Authorization字段,验证JWT令牌,并在验证成功后将用户信息放入Spring Security的上下文中。

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

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

深知大多数网络安全工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年网络安全全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img
img

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

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

如果你觉得这些内容对你有帮助,可以添加VX:vip204888 (备注网络安全获取)
img

还有兄弟不知道网络安全面试可以提前刷题吗?费时一周整理的160+网络安全面试题,金九银十,做网络安全面试里的显眼包!

王岚嵚工程师面试题(附答案),只能帮兄弟们到这儿了!如果你能答对70%,找一个安全工作,问题不大。

对于有1-3年工作经验,想要跳槽的朋友来说,也是很好的温习资料!

【完整版领取方式在文末!!】

93道网络安全面试题

内容实在太多,不一一截图了

黑客学习资源推荐

最后给大家分享一份全套的网络安全学习资料,给那些想学习 网络安全的小伙伴们一点帮助!

对于从来没有接触过网络安全的同学,我们帮你准备了详细的学习成长路线图。可以说是最科学最系统的学习路线,大家跟着这个大的方向学习准没问题。

1️⃣零基础入门
① 学习路线

对于从来没有接触过网络安全的同学,我们帮你准备了详细的学习成长路线图。可以说是最科学最系统的学习路线,大家跟着这个大的方向学习准没问题。

image

② 路线对应学习视频

同时每个成长路线对应的板块都有配套的视频提供:

image-20231025112050764

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

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

t/forums/4304bb5a486d4c3ab8389e65ecb71ac0)

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

  • 12
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
uniapp 基于 Spring Security 实现密码模式登录的完整代码如下: 1. 后端代码 首先需要在后端实现一个登录接口,用于接收前端传递过来的用户名和密码,并返回相应的登录结果。这里使用 Spring Security 实现密码模式登录,需要在 SecurityConfig 中进行相关配置。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginProcessingUrl("/login") .usernameParameter("username") .passwordParameter("password") .successHandler(authenticationSuccessHandler()) .failureHandler(authenticationFailureHandler()) .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessHandler(logoutSuccessHandler()) .permitAll() .and() .csrf().disable(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationSuccessHandler authenticationSuccessHandler() { return new CustomAuthenticationSuccessHandler(); } @Bean public AuthenticationFailureHandler authenticationFailureHandler() { return new CustomAuthenticationFailureHandler(); } @Bean public LogoutSuccessHandler logoutSuccessHandler() { return new CustomLogoutSuccessHandler(); } } ``` 2. 前端代码 在前端代码中,需要实现一个登录页面,用于接收用户输入的用户名和密码,并将其发送到后端进行验证。以下是一个简单的登录页面示例: ``` <template> <view class="container"> <input type="text" v-model="username" placeholder="用户名"> <input type="password" v-model="password" placeholder="密码"> <button @click="login">登录</button> </view> </template> <script> export default { data() { return { username: '', password: '' } }, methods: { login() { uni.request({ url: '/login', method: 'POST', data: { username: this.username, password: this.password }, success: function(res) { uni.showToast({ title: '登录成功', icon: 'success' }) }, fail: function(res) { uni.showToast({ title: '登录失败,请重试', icon: 'none' }) } }) } } } </script> ``` 在登录按钮的点击事件中,使用 uni.request 方法向后端发送 POST 请求,将用户名和密码作为请求体发送到后端进行验证。如果验证成功,后端会返回一个登录成功的响应,否则返回一个登录失败的响应。 需要注意的是,在进行跨域请求时,需要在后端进行相应的配置,允许前端访问后端接口。可以使用 @CrossOrigin 注解或者在 WebMvcConfigurer 中进行配置。 以上就是 uniapp 基于 Spring Security 实现密码模式登录的完整代码,其中包括了后端的 SecurityConfig 配置和前端的登录页面示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值