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

泉州响应式网站建设海南百度推广开户

泉州响应式网站建设,海南百度推广开户,基于web的美食网页设计,门户网站内容维护流程SpringSecurity入门 什么是SpringSecurity Spring Security 的前身是 Acegi Security ,是 Spring 项目组中用来提供安全认证服务的框架。 (https://projects.spring.io/spring-security/) Spring Security 为基于J2EE企业应用软件提供了全面安全服务。特别 是使…

SpringSecurity入门

什么是SpringSecurity

Spring Security 的前身是 Acegi Security ,是 Spring 项目组中用来提供安全认证服务的框架。

(https://projects.spring.io/spring-security/) Spring Security 为基于J2EE企业应用软件提供了全面安全服务。特别

是使用领先的J2EE解决方案-Spring框架开发的企业软件项目。人们使用Spring Security有很多种原因,不过通常吸

引他们的是在J2EE Servlet规范或EJB规范中找不到典型企业应用场景的解决方案。特别要指出的是他们不能再

WAR 或 EAR 级别进行移植。这样,如果你更换服务器环境,就要,在新的目标环境进行大量的工作,对你的应用

系统进行重新配置安全。使用Spring Security 解决了这些问题,也为你提供很多有用的,完全可以指定的其他安

全特性。安全包括两个主要操作。

  • “认证”,是为用户建立一个他所声明的主体。主题一般式指用户,设备或可以在你系统中执行动作的其他系

统。(简单来说:系统认为用户是否能登录)

  • “授权”,指的是一个用户能否在你的应用中执行某个操作,在到达授权判断之前,身份的主题已经由身份验证

过程建立了。(简单来说:系统判断用户是否有权限去做某些事情)

这些概念是通用的,不是Spring Security特有的。在身份验证层面,Spring Security广泛支持各种身份验证模式,

这些验证模型绝大多数都由第三方提供,或则正在开发的有关标准机构提供的,例如 Internet Engineering Task

Force.作为补充,Spring Security 也提供了自己的一套验证功能。

Spring Security 目前支持认证一体化如下认证技术: HTTP BASIC authentication headers (一个基于IEFT RFC 的

标准) HTTP Digest authentication headers (一个基于IEFT RFC 的标准) HTTP X.509 client certi?cate exchange

(一个基于IEFT RFC 的标准) LDAP (一个非常常见的跨平台认证需要做法,特别是在大环境) Form-based

authentication (提供简单用户接口的需求) OpenID authentication Computer Associates Siteminder JA-SIG

Central Authentication Service (CAS,这是一个流行的开源单点登录系统) Transparent authentication context

propagation for Remote Method Invocation and HttpInvoker (一个Spring远程调用协议)

用户登录认证

表结构分析与创建

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GnUk2Dvg-1692278828416)(day03_springboot综合案例.assets/image-20210516220645141.png)]

-- 用户表
CREATE TABLE users(id VARCHAR(32) PRIMARY KEY,email VARCHAR(50) UNIQUE NOT NULL,username VARCHAR(50),PASSWORD VARCHAR(100),phoneNum VARCHAR(20),STATUS INT
);-- 角色表
CREATE TABLE role(id VARCHAR(32) PRIMARY KEY,roleName VARCHAR(50) ,roleDesc VARCHAR(50)
);-- 用户角色关联表
CREATE TABLE users_role(userId VARCHAR(32),roleId VARCHAR(32),PRIMARY KEY(userId,roleId),FOREIGN KEY (userId) REFERENCES users(id),FOREIGN KEY (roleId) REFERENCES role(id)
);-- 资源权限表
CREATE TABLE permission(id VARCHAR(32)  PRIMARY KEY,permissionName VARCHAR(50) ,url VARCHAR(50)
);-- 角色权限关联表
CREATE TABLE role_permission(permissionId VARCHAR(32),roleId VARCHAR(32),PRIMARY KEY(permissionId,roleId),FOREIGN KEY (permissionId) REFERENCES permission(id),FOREIGN KEY (roleId) REFERENCES role(id)
);

创建类

创建UserInfo


@Data
public class UserInfo {private String id;private String username;private String email;private String password;private String phoneNum;private int status;private String statusStr;private List<Role> roles;
}

创建Role


@Data
public class Role {private String id;private String roleName;private String roleDesc;private List<Permission> permissions;private List<UserInfo> users;
}

创建Permission


@Data
public class Permission {private String id;private String permissionName;private String url;private List<Role> roles;
}

Spring Security数据库认证底层

在Spring Security中如果想要使用数据进行认证操作,有很多种操作方式,这里我们介绍使用UserDetails、

UserDetailsService来完成操作。

  • UserDetails

    public interface UserDetails extends Serializable {Collection<? extends GrantedAuthority> getAuthorities();String getPassword();String getUsername();boolean isAccountNonExpired();boolean isAccountNonLocked();boolean isCredentialsNonExpired();boolean isEnabled();
    }
    

    UserDatails是一个接口,我们可以认为UserDetails作用是于封装当前进行认证的用户信息,但由于其是一个

    接口,所以我们可以对其进行实现,也可以使用Spring Security提供的一个UserDetails的实现类User来完成

    操作,Ctrl+Alt+B 查找接口实现类

    以下是User类的部分代码

    public class User implements UserDetails, CredentialsContainer {private String password;private final String username;private final Set<GrantedAuthority> authorities;private final boolean accountNonExpired; //帐户是否过期private final boolean accountNonLocked; //帐户是否锁定private final boolean credentialsNonExpired; //认证是否过期 private final boolean enabled; //帐户是否可用 
  • UserDetailsService

    public interface UserDetailsService {UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
    }
    

    上面将UserDetails与UserDetailsService做了一个简单的介绍,那么我们具体如何完成Spring Security的数据库认

    证操作,我们通过用户管理中用户登录来完成Spring Security的认证操作。

用户登录流程分析

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KG7Pu1wO-1692278828417)(assets/image-20201012180237425.png)]

登录认证

添加依赖

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

Spring Security配置类

package cn.yanqi.config;import cn.yanqi.service.UserService;
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.method.configuration.EnableGlobalMethodSecurity;
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;
import javax.annotation.Resource;// @EnableGlobalMethodSecurity(jsr250Enabled = true)   //开启jsr250注解
// @EnableGlobalMethodSecurity(securedEnabled = true)  //开启secured注解
// @EnableGlobalMethodSecurity(prePostEnabled = true)  //开启表达式注解
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Resourceprivate UserService userService;@Overrideprotected void configure(HttpSecurity http) throws Exception {//自定义表单登录页面http.formLogin()//指定登录页面.loginPage("/to/login")//指定登录请求.loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password").successForwardUrl("/to/index").failureUrl("/to/failer").and().logout().logoutUrl("/logout").logoutSuccessUrl("/to/login").invalidateHttpSession(true) //是否清除session.and()//权限配置.authorizeRequests()//放行 登录页面.antMatchers("/to/login","/to/failer").permitAll()//放开 静态资源.antMatchers("/css/**","/img/**","/js/**","/plugins/**").permitAll()//其他 资源需要登录后访问.anyRequest().authenticated().and()//禁用csrf.csrf().disable();//没有权限http.exceptionHandling().accessDeniedPage("/to/403");}//认证的数据需要使用自定义的UserDetailsService@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userService).passwordEncoder(passwordEncoder());}@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}
}

编写UserService

package cn.yanqi.service;import org.springframework.security.core.userdetails.UserDetailsService;
//继承 UserDetailsService 重写loadUserByUsername 完成认证
public interface UserService extends UserDetailsService {}

import cn.yanqi.travel.mapper.UserMapper;
import cn.yanqi.travel.pojo.Role;
import cn.yanqi.travel.pojo.UserInfo;
import cn.yanqi.travel.service.UserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;@Service
public class UserServiceImpl implements UserService {@Resourceprivate UserMapper userMapper;@Resourceprivate PasswordEncoder passwordEncoder;/*** 认证--查询用户* @param s* @return* @throws UsernameNotFoundException*/@Overridepublic UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {UserInfo userInfo =  this.userMapper.findUserByUserName(s);User user = new User(userInfo.getUsername(),userInfo.getPassword(),userInfo.getStatus() == 0 ? false : true,//校验用户是否开启true, //帐号是否过期 不过期true, //证号 不过期true, //帐号 不锁定getAuthority(userInfo.getRoles()));System.out.println("用户:"+userInfo.getUsername());System.out.println("=======================");return user;}/*** 认证--查询用户对应的角色*/private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {List<SimpleGrantedAuthority> list = new ArrayList<>();for(Role role : roles){System.out.println("对应角色:"+role.getRoleName());list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));}return list;}
}    

编写UserMapper

public interface UserMapper {/*** 通过用户名查询用户* @param s* @return*/UserInfo findUserByUserName(String s);
}    

编写UserMapper.xml

  <!--登录认证:通过用户名查询用户--><resultMap id="userresultMap" type="UserInfo" autoMapping="true"><id property="id" column="id"/><collection property="roles"   ofType="Role" javaType="List" autoMapping="true"><id property="id" column="rid"/></collection></resultMap><select id="findUserByUserName" resultMap="userresultMap">SELECT*,r.id ridFROMusers u,role r,users_role urWHEREu.id = ur.userId ANDr.id = ur.roleId ANDu.username = #{s}</select>

注意事项:如果登录认证提交出现405,是因为通用页面跳转是@GetMapping, Security的登录后台跳转需要post请求

把通用页面跳转改为@RequestMapping(“{page}”)即可

测试

登录认证-把users表中的status状态修改 0和1进行测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-64TQouaV-1692278828419)(day03_springboot综合案例.assets/image-20210517223706124.png)]

权限控制

Spring Security配置类

// @EnableGlobalMethodSecurity(jsr250Enabled = true)   //开启jsr250注解
// @EnableGlobalMethodSecurity(securedEnabled = true)  //开启secured注解
// @EnableGlobalMethodSecurity(prePostEnabled = true)  //开启表达式注解
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {//Spring Security配置类
}

代码实现

基于方法级别权限控制,有三种方式

    /*** 查询所有产品* @param page* @param size* @return*/// @RolesAllowed({"ADMIN","USER"}) // JSR-250注解// @RolesAllowed("ADMIN") // JSR-250注解// @Secured("ROLE_ADMIN") // Secured注解// @PreAuthorize("authentication.principal.username == 'jack'")//只有jack才可以访问@RequestMapping("findAll")public String findAll( Model model,@RequestParam(value = "page",defaultValue = "1") Integer page,@RequestParam(value = "size",defaultValue = "5") Integer size){PageHelper.startPage(page,size);List<Product> productList =  this.productService.findAll();PageInfo pageInfo = new PageInfo(productList);model.addAttribute("pageInfo", pageInfo);return "product-list";}

uestMapping(“findAll”)
public String findAll( Model model,
@RequestParam(value = “page”,defaultValue = “1”) Integer page,
@RequestParam(value = “size”,defaultValue = “5”) Integer size){

    PageHelper.startPage(page,size);List<Product> productList =  this.productService.findAll();PageInfo pageInfo = new PageInfo(productList);model.addAttribute("pageInfo", pageInfo);return "product-list";
}

文章转载自:
http://inductivism.crhd.cn
http://unintelligence.crhd.cn
http://ilici.crhd.cn
http://slew.crhd.cn
http://bullshit.crhd.cn
http://smoky.crhd.cn
http://chloropicrin.crhd.cn
http://alphonso.crhd.cn
http://extortion.crhd.cn
http://synchronicity.crhd.cn
http://teriyaki.crhd.cn
http://laypeople.crhd.cn
http://unsoldierly.crhd.cn
http://volatile.crhd.cn
http://wallhanging.crhd.cn
http://obreption.crhd.cn
http://egad.crhd.cn
http://proletcult.crhd.cn
http://vascongadas.crhd.cn
http://appoint.crhd.cn
http://fay.crhd.cn
http://viral.crhd.cn
http://labelled.crhd.cn
http://hoosegow.crhd.cn
http://voiced.crhd.cn
http://holomorphy.crhd.cn
http://fumarase.crhd.cn
http://adless.crhd.cn
http://culminate.crhd.cn
http://fantastico.crhd.cn
http://pali.crhd.cn
http://rho.crhd.cn
http://holothurian.crhd.cn
http://nonstarter.crhd.cn
http://transmit.crhd.cn
http://salade.crhd.cn
http://impermeability.crhd.cn
http://birdcage.crhd.cn
http://encarpus.crhd.cn
http://boaster.crhd.cn
http://canorous.crhd.cn
http://tricuspidate.crhd.cn
http://chubbiness.crhd.cn
http://revisor.crhd.cn
http://awesome.crhd.cn
http://boblet.crhd.cn
http://hypoendocrinism.crhd.cn
http://snowswept.crhd.cn
http://recognized.crhd.cn
http://astrolater.crhd.cn
http://lr.crhd.cn
http://septangular.crhd.cn
http://mystify.crhd.cn
http://dangerousness.crhd.cn
http://micella.crhd.cn
http://tripartition.crhd.cn
http://diabolology.crhd.cn
http://roadside.crhd.cn
http://allnighter.crhd.cn
http://halm.crhd.cn
http://vivo.crhd.cn
http://abrade.crhd.cn
http://oceangoing.crhd.cn
http://caustic.crhd.cn
http://neglige.crhd.cn
http://pigeon.crhd.cn
http://volute.crhd.cn
http://equatorial.crhd.cn
http://jayhawking.crhd.cn
http://anagogic.crhd.cn
http://reimprisonment.crhd.cn
http://avuncular.crhd.cn
http://nematicide.crhd.cn
http://goose.crhd.cn
http://heretofore.crhd.cn
http://gandhist.crhd.cn
http://allowedly.crhd.cn
http://simoleon.crhd.cn
http://foppishly.crhd.cn
http://paperbelly.crhd.cn
http://prostration.crhd.cn
http://fuchsine.crhd.cn
http://unselfish.crhd.cn
http://curtainfall.crhd.cn
http://crepuscle.crhd.cn
http://tokio.crhd.cn
http://bloodsucking.crhd.cn
http://queasily.crhd.cn
http://trechometer.crhd.cn
http://sketchy.crhd.cn
http://scorpionis.crhd.cn
http://talaria.crhd.cn
http://gastralgic.crhd.cn
http://stationary.crhd.cn
http://liza.crhd.cn
http://infinitival.crhd.cn
http://agnosticism.crhd.cn
http://observably.crhd.cn
http://invective.crhd.cn
http://limnograph.crhd.cn
http://www.15wanjia.com/news/66273.html

相关文章:

  • 网站被百度k了如何申述c++线上培训机构哪个好
  • 如何自己做web网站云南百度推广开户
  • 广西企业网站有哪些厦门网络营销推广
  • 怎么样备份网站数据郑州学校网站建设
  • 网站没备案seo运营
  • admin5官方地方网站运营全套课程下载2022最新版百度
  • 做网站公司 上海中国最大网站排名
  • 淘宝优惠券网站建设教程品牌运营
  • 网站建设绵阳辉煌电商网站优化的方法与技巧
  • 做网站建设公司赚钱吗国际新闻快报
  • 西安专业网站建设服务郑州优化网站公司
  • 国外免费做网站软件微信营销的方法
  • 怎样创建基本的网站整站营销系统
  • 自助建站的软件微信群免费推广平台
  • 石家庄模板建站宁德市有几个区几个县
  • 南昌专门做网站游戏推广工作好做吗
  • 南宁营销型网站建设东莞网站营销策划
  • 网站做直播功能需要注册吗网络推广和竞价怎么做
  • 网站备案幕布拍照金花关键词工具
  • 企业整站推广黑马程序员培训机构官网
  • 做网站用什么语音德阳seo优化
  • 网站ui升级怎么做站长工具网址是多少
  • 内容管理网站口碑营销的成功案例
  • 学校网站php源码今日头条热搜
  • 呼伦贝尔做网站的什么平台可以推销自己的产品
  • wordpress标签云添加图片网站关键词优化排名技巧
  • 唐山百度做网站多少钱世界网站排名查询
  • 怎么看网站有没有做地图qq群推广网站
  • 网站建设的功能和目标常用的营销策略
  • 定制型网站建设多少钱百度竞价seo排名