当前位置: 首页 > news >正文

福彩网网站建设方案一级消防工程师考试难度

福彩网网站建设方案,一级消防工程师考试难度,企业网站哪里可以做,南京市建设发展集团有限公司网站Spring Boot中的安全配置与实现 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将深入探讨Spring Boot中的安全配置与实现,看看如何保护你的…

Spring Boot中的安全配置与实现

大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将深入探讨Spring Boot中的安全配置与实现,看看如何保护你的应用免受潜在的安全威胁。

一、Spring Boot中的安全框架简介

Spring Boot集成了Spring Security,这是一个强大的认证和授权框架,用于保护基于Spring的应用程序。Spring Security提供了许多功能,如基于角色的访问控制、表单登录、HTTP Basic认证、OAuth 2.0支持等。

1. Maven依赖

首先,确保在pom.xml文件中添加Spring Security的依赖:

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

二、基本的安全配置

1. 创建安全配置类

创建一个继承自WebSecurityConfigurerAdapter的配置类,用于定义安全策略。

package cn.juwatech.springboot.config;import org.springframework.context.annotation.Bean;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasRole("USER").anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

2. 配置登录页面

创建一个简单的登录页面login.html,放置在src/main/resources/templates目录下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Login</title>
</head>
<body><div><h2>Login</h2><form th:action="@{/login}" method="post"><div><label>Username: <input type="text" name="username"></label></div><div><label>Password: <input type="password" name="password"></label></div><div><input type="submit" value="Sign in"></div></form></div>
</body>
</html>

三、基于注解的安全控制

Spring Security支持基于注解的安全控制,使用@PreAuthorize@Secured注解可以在方法级别进行权限控制。

1. 使用@Secured注解

在服务类的方法上使用@Secured注解,指定角色权限。

package cn.juwatech.springboot.service;import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;@Service
public class UserService {@Secured("ROLE_ADMIN")public String adminMethod() {return "Admin access only";}@Secured("ROLE_USER")public String userMethod() {return "User access only";}
}

2. 使用@PreAuthorize注解

使用@PreAuthorize注解支持SpEL(Spring Expression Language)表达式,实现更复杂的权限控制。

package cn.juwatech.springboot.service;import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;@Service
public class SecureService {@PreAuthorize("hasRole('ADMIN')")public String adminOnly() {return "Admin access only";}@PreAuthorize("hasRole('USER') and #id == principal.id")public String userOnly(Long id) {return "User access for ID: " + id;}
}

四、使用JWT进行安全认证

JWT(JSON Web Token)是一种轻量级的认证机制,常用于移动和Web应用的认证。

1. 添加JWT依赖

pom.xml中添加JWT相关依赖:

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>

2. 创建JWT工具类

实现一个JWT工具类,负责生成和解析JWT。

package cn.juwatech.springboot.security;import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;import java.util.Date;@Component
public class JwtUtil {private String secretKey = "secret";public String generateToken(String username) {return Jwts.builder().setSubject(username).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)).signWith(SignatureAlgorithm.HS256, secretKey).compact();}public Claims extractClaims(String token) {return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();}public String extractUsername(String token) {return extractClaims(token).getSubject();}public boolean isTokenExpired(String token) {return extractClaims(token).getExpiration().before(new Date());}public boolean validateToken(String token, String username) {return (username.equals(extractUsername(token)) && !isTokenExpired(token));}
}

3. 集成JWT认证

在Spring Security配置中集成JWT认证。

package cn.juwatech.springboot.config;import cn.juwatech.springboot.security.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate JwtUtil jwtUtil;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasRole("USER").anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);http.addFilterBefore(new JwtRequestFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

四、总结

通过本文,我们全面了解了在Spring Boot中实现安全配置的各种方法,包括基本的安全配置、基于注解的权限控制以及如何集成JWT进行认证。Spring Security提供了丰富的功能,使得应用程序的安全性得到有效保障。

微赚淘客系统3.0小编出品,必属精品!

http://www.yayakq.cn/news/917287/

相关文章:

  • 长春网站建设58同城误入网站退不了怎么做
  • 厦门网站建设团队四会市住房和城乡建设局网站
  • 专业商城网站建设公司新云自助建站
  • 为什么需要建设网站网站链接分享做推广
  • 摄影图片素材网站wordpress插件清单 很多很全
  • 章丘区当地网站建设哪家好临沂做网站的公司有哪些
  • 网上做设计兼职哪个网站好点高端网站建设推广
  • 南京网站设计培训价格上海公司电话
  • 旅游电子商务网站的建设方案wordpress支持
  • 建设垂直网站需要哪些流程网推公司怎么收费
  • 进入江苏省住房和城乡建设厅网站首页wordpress-5.0升级未被安装
  • 在线做家装设计的网站怎么知道网站是什么开源做的
  • 漳州做网站匹配博大钱少a网站设计制作的服务商
  • 在线考试网站开发报价无锡做网站公司在哪里
  • div网站模板门户网站首页设计
  • 电商网站开发教材免费空间 个人网站 google广告联盟
  • 企业更新网站的好处自媒体135app下载
  • 网站建设过程总结报告大气简洁网站
  • 如何弄一个网站建立一个网站赚钱了
  • 平湖公司网站建设ui设计稿
  • 购物网站建设 成都软件开发交付流程
  • asp.net+mvc+网站开发电气营销型网站方案
  • 用动易建设网站教程可以在线观看的免费资源
  • 网站推广软件app许昌网络推广公司
  • 网站推广公司水果茶优化设计六年级下册语文答案
  • 河北省住房和城乡建设厅网站首页网站建设网站及上传
  • 提供手机网站开发创新网站建设工作室
  • 制作网站步骤广州网站优化效果
  • 漯河做网站公司东莞大岭山属于哪个镇
  • 类似pc蛋蛋的网站建设网站流量 seo