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

宝安网站设计养殖企业网站

宝安网站设计,养殖企业网站,徐州网站开发多少钱,商丘梁园区Spring Boot中的安全配置与实现 大家好#xff0c;我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编#xff0c;也是冬天不穿秋裤#xff0c;天冷也要风度的程序猿#xff01;今天我们将深入探讨Spring Boot中的安全配置与实现#xff0c;看看如何保护你的…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的依赖 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-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:thhttp://www.thymeleaf.org headtitleLogin/title /head bodydivh2Login/h2form th:action{/login} methodpostdivlabelUsername: input typetext nameusername/label/divdivlabelPassword: input typepassword namepassword/label/divdivinput typesubmit valueSign 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注解支持SpELSpring 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进行安全认证 JWTJSON Web Token是一种轻量级的认证机制常用于移动和Web应用的认证。 1. 添加JWT依赖 在pom.xml中添加JWT相关依赖 dependencygroupIdio.jsonwebtoken/groupIdartifactIdjjwt/artifactIdversion0.9.1/version /dependency2. 创建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.w-s-a.com/news/549588/

相关文章:

  • 网站备案要营业执照吗网站建设如何记账
  • 新手学做网站难吗外包服务商
  • 公司网站建设的项目工作分解结构wordpress插件后端页面
  • 四川省建设人才网站2018南京专业建站
  • ppt制作网站推荐seo教程百度网盘
  • 网站建设多少钱一平米网上商城网站开发报告
  • 福州网站建设招聘信息哈尔滨中企动力科技股份有限公司
  • 军事新闻最新seo关键词查询排名软件
  • 免费网站建设官网项目建设表态发言
  • 平谷建站推广广告投放平台主要有哪些
  • 网站备案掉了什么原因步骤怎么读
  • 徐州市建设监理协会网站做一个公司官网需要多少钱
  • 网站开发学什么数据库做公司网站注意事项
  • 游戏开发网站建设国际战事最新消息
  • 达州+网站建设网站里自己怎么做推广
  • 看网站建设公司的网站案例熊掌号接入wordpress
  • 黄石下陆区建设局网站wordpress如何拖移小工具
  • 宁波网站建设信息网站开发看书
  • 网站建设优化价格北京优化seo排名
  • 微信网站建设公司费用高端网站建设 炫酷
  • 北京网站假设销售找客户最好的app
  • 做外贸需要关注的网站有什么好处宜州设计公司
  • 公司最近想做个网站怎么办陕西科强建设工程有限公司官方网站
  • 生态城门户网站 建设动态it外包收费
  • 网站项目评价老渔哥网站建设公司
  • 哈尔滨寸金网站建设价格178软文网
  • 一个网站建设的成本网站开发过程及要点
  • 监控视频做直播网站中国建筑人才网下载
  • 网站建设公司华网天下买送活动集团网站设计案例
  • 哪些网站比较容易做哪个网站做中高端衣服