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

顶岗实践网站开发财务公司业务范围

顶岗实践网站开发,财务公司业务范围,赣州市规划建设局网站改,wordpress本地打不开前言 本篇为大家带来Spring security的授权#xff0c;首先要理解一些概念#xff0c;有关于#xff1a;权限、角色、安全上下文、访问控制表达式、方法级安全性、访问决策管理器 一.授权的基本介绍 Spring Security 中的授权分为两种类型#xff1a; 基于角色的授权首先要理解一些概念有关于权限、角色、安全上下文、访问控制表达式、方法级安全性、访问决策管理器 一.授权的基本介绍 Spring Security 中的授权分为两种类型 基于角色的授权以用户所属角色为基础进行授权如管理员、普通用户等通过为用户分配角色来控制其对资源的访问权限。 基于资源的授权以资源为基础进行授权如 URL、方法等通过定义资源所需的权限来控制对该资源的访问权限。 Spring Security 提供了多种实现授权的机制最常用的是使用基于注解的方式建立起访问资源和权限之间的映射关系。 其中最常用的两个注解是 Secured 和 PreAuthorize。Secured 注解是更早的注解基于角色的授权比较适用PreAuthorize 基于 SpEL 表达式的方式可灵活定义所需的权限通常用于基于资源的授权。 二.修改User配置角色和权限 方法一. 使用SQL语句的方式查询该角色的权限并且可以对它进行修改 根据用户id查询出对应的角色信息 SELECT*FROMsys_user a,sys_user_role b,sys_role_module c,sys_module dWHERE a.id b.user_id andb.role_idc.role_id andc.module_id d.id anda.id#{id} 根据用户ID查询出角色对应的权限信息 selectm.url fromsys_user u,sys_user_role ur,sys_role r,sys_role_module rm,sys_module m whereu.idur.userid and ur.roleidr.roleid andr.roleidrm.roleid and rm.moduleidm.id andu.id#{userid} and url is not null 但是并不推荐使用这种方法当我们在实际开发中要考虑到不同的数据表可能来自不同的库中使用SQL查询时就会出现链表查询不同库的表的情况所以更多的时候我们会使用Java利用不同的操作对表进行依次查询作为条件最终得到结果 方法二.利用Java对表单一查询然后作为查询条件最终查询出结果 Service public class UserServiceImpl extends ServiceImplUserMapper, User implements IUserService, UserDetailsService {Autowiredprivate IUserRoleService userRoleService;Autowiredprivate IRoleService roleService;Autowiredprivate IRoleModuleService roleModuleService;Autowiredprivate IModuleService moduleService;Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user getOne(new QueryWrapperUser().eq(username, username));if(usernull){throw new UsernameNotFoundException(用户名无效);}//查询出身份//map遍历所有对象返回新的数据放到新的集合中//filter 过滤流中的内容//collect将流中的元素变成一个集合ListInteger role_ids userRoleService.list(new QueryWrapperUserRole().eq(user_id, user.getId())).stream().map(UserRole::getRoleId).collect(Collectors.toList());//根据身份字段查询身份对应的名字字段ListString roles roleService.list(new QueryWrapperRole()).stream().map(Role::getRoleName).collect(Collectors.toList());//根据身份id查询具备的权限idListInteger module_ids roleModuleService.list(new QueryWrapperRoleModule().in(role_id, role_ids)).stream().map(RoleModule::getModuleId).collect(Collectors.toList());//根据权限id查询对应的权限ListString modules moduleService.list(new QueryWrapperModule().in(id, module_ids)).stream().map(Module::getUrl).collect(Collectors.toList());// 将权限字段加到身份中roles.addAll(modules);//将当前集合内容加到权限字段中ListSimpleGrantedAuthority authorities roles.stream().map(SimpleGrantedAuthority::new).filter(Objects::nonNull).collect(Collectors.toList());user.setAuthorities(authorities);return user;} } 三.SpringSecurity配置类 当我们想要开启spring方法级安全时只需要在任何 Configuration实例上使用EnableGlobalMethodSecurity 注解就能达到此目的。同时这个注解为我们提供了prePostEnabled 、securedEnabled 和 jsr250Enabled 三种不同的机制来实现同一种功能。 修改WebSecurityConfig配置类开启基于方法的安全认证机制也就是说在web层的controller启用注解机制的安全确认。 Configuration EnableWebSecurity EnableGlobalMethodSecurity(prePostEnabled true) public class WebSecurityConfig {Autowiredprivate UserServiceImpl userDetailsService;Autowiredprivate ObjectMapper objectMapper;Autowiredprivate MyAuthenticationFailureHandler myAuthenticationFailureHandler;Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}Beanpublic AuthenticationManager authenticationManager() throws Exception {//创建DaoAuthenticationProviderDaoAuthenticationProvider provider new DaoAuthenticationProvider();//设置userDetailsService基于数据库方式进行身份认证provider.setUserDetailsService(userDetailsService);//配置密码编码器provider.setPasswordEncoder(passwordEncoder());return new ProviderManager(provider);}Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeRequests()//antMatchers 匹配对应的路径//permitAll 允许.antMatchers(/).permitAll()//anyRequest 其余所有请求//authenticated 登录.anyRequest().authenticated().and().formLogin()//loginPage 登录页面.loginPage(/)//设置处理登录请求的接口.loginProcessingUrl(/userLogin)//用户的数据的参数.usernameParameter(username).passwordParameter(password)//登录成功.successHandler((req, resp, auth) - {Object user auth.getPrincipal();objectMapper.writeValue(resp.getOutputStream(), JsonResponseBody.success(user));})//登录失败.failureHandler(myAuthenticationFailureHandler).and().exceptionHandling()//权限不足.accessDeniedHandler((req, resp, ex) - {objectMapper.writeValue(resp.getOutputStream(), JsonResponseBody.other(JsonResponseStatus.NO_ACCESS));})//没有认证.authenticationEntryPoint((req, resp, ex) - {objectMapper.writeValue(resp.getOutputStream(), JsonResponseBody.other(JsonResponseStatus.NO_LOGIN));}).and().logout().logoutUrl(/logout).logoutSuccessUrl(/);http.csrf().disable();return http.build();}} 这里需要注意的是EnableGlobalMethodSecurity是Spring Security提供的一个注解用于启用方法级别的安全性。它可以在任何Configuration类上使用以启用Spring Security的方法级别的安全性功能。它接受一个或多个参数用于指定要使用的安全注解类型和其他选项。以下是一些常用的参数 prePostEnabled如果设置为true则启用PreAuthorize和PostAuthorize注解。默认值为false。 securedEnabled如果设置为true则启用Secured注解。默认值为false。 jsr250Enabled如果设置为true则启用RolesAllowed注解。默认值为false。 proxyTargetClass如果设置为true则使用CGLIB代理而不是标准的JDK动态代理。默认值为false。 使用EnableGlobalMethodSecurity注解后可以在应用程序中使用Spring Security提供的各种注解来保护方法例如Secured、PreAuthorize、PostAuthorize和RolesAllowed。这些注解允许您在方法级别上定义安全规则以控制哪些用户可以访问哪些方法。 注解介绍 注解说明PreAuthorize用于在方法执行之前对访问进行权限验证PostAuthorize用于在方法执行之后对返回结果进行权限验证Secured用于在方法执行之前对访问进行权限验证RolesAllowed是Java标准的注解之一用于在方法执行之前对访问进行权限验证 四.管理控制Controller层的权限 Controller public class IndexController {RequestMapping(/)public String toLogin() {return login;}RequestMapping(/userLogin)public String userLogin() {return index;}RequestMapping(/index)public String toIndex() {return index;}RequestMapping(/noAccess)public String noAccess() {return accessDenied;}ResponseBodyRequestMapping(/order_add)PreAuthorize(hasAuthority(order:manager:add))public String order_add() {return 订单新增;}ResponseBodyPreAuthorize(hasAuthority(book:manager:add))RequestMapping(/book_add)public String book_add() {return 书本新增;}} 在当前登录的用户必须拥有当前的权限字段才能进行访问例如book:manager:add 五.异常处理 AccessDeniedHandler是Spring Security提供的一个接口用于处理访问被拒绝的情况。当用户尝试访问受保护资源但没有足够的权限时Spring Security会调用AccessDeniedHandler来处理这种情况。 AccessDeniedHandler接口只有一个方法handle()该方法接收HttpServletRequest、HttpServletResponse和AccessDeniedException三个参数。在handle()方法中可以自定义响应的内容例如返回一个自定义的错误页面或JSON响应。 创建AccessDeniedHandlerImpl类并实现AccessDeniedHandler接口实现自定义的JSON响应。例如 package com.yu.security.resp;import lombok.Getter;Getter public enum JsonResponseStatus {OK(200, OK),UN_KNOWN(500, 未知错误),RESULT_EMPTY(1000, 查询结果为空),NO_ACCESS(3001, 没有权限),NO_LOGIN(4001, 没有登录),LOGIN_FAILURE(5001, 登录失败),;private final Integer code;private final String msg;JsonResponseStatus(Integer code, String msg) {this.code code;this.msg msg;}}单独写一个接口进行实现并将出现异常后的操作在里面实现 package com.yu.security.config;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.fasterxml.jackson.databind.ObjectMapper; import com.yu.security.pojo.User; import com.yu.security.resp.JsonResponseBody; import com.yu.security.resp.JsonResponseStatus; import com.yu.security.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.stereotype.Component;import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;Component public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {Autowiredprivate ObjectMapper objectMapper;// 在redis中定义一个键当登录失败是就对那个键的值进行加一//如果大于三就锁住Autowiredprivate IUserService userService;Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {if(12){User user userService.getOne(new QueryWrapperUser().eq(username, request.getParameter(username)));user.setAccountNonLocked(false);userService.updateById(user);}objectMapper.writeValue(response.getOutputStream(), JsonResponseBody.other(JsonResponseStatus.LOGIN_FAILURE));}}在当前例子中我们通过在配置类引入当前接口并实现当前接口在实现类中对登录失败进行 对应的操作在Redis中定义一个键当登录失败是就对那个键的值进行加一,如果大于三就对当前账号进行冻结
http://www.sadfv.cn/news/44543/

相关文章:

  • 做网站销售有前景吗配件查询网站制作
  • python 做办公网站深圳宝安区1例确诊
  • 平顶山建设局网站网络策划主要做什么
  • 安阳网站优化wordpress创建自定义页面模板
  • 局域网视频网站搭建教育类app开发价格表
  • 贵港网站制作建网站找哪里
  • 湖州南浔建设局网站wordpress菜伪静态
  • 给帅哥做奴视频网站网站开发协同
  • 有哪些网站是静态网站直播网站 建设
  • 电影网站怎么做友情链接wordpress 留言板代码
  • 做旅游网站宣传装饰公司营销型网站建设
  • 沈阳做网站的科技公司汽车之家官网首页
  • 网站专题欣赏网站备案注意
  • 网站建设肆金手指排名6岳阳品牌网站定制开发
  • 黑色网站设计邹城网站制作
  • 知名小蚁人网站建设中国房地产排名100强
  • 苏州网络推广公司网站建设佛山南海区建设局网站
  • 网站上做旅游卖家要学什么免费的中文logo网站
  • 公司网站制作知乎网站开发需要注册几类商标
  • 毕设做网站具体步骤一键生成简历
  • 济源新站seo关键词排名推广中国建设承包商网站
  • 北京网站建设公司完美湖南岚鸿首 选wordpress投票主题
  • 湖南建设局网站网站做支付宝接口
  • 阿里巴巴网站建设的功能定位利用小说网站做本站优化
  • shopnc本地生活o2o网站系统网站建设公司怎么找业务
  • 外贸网站建设收益电商软件开发平台
  • 网站改版怎样做301网站建设需要了解的信息
  • 网站中的幻灯片ie6显示 ie7如何兼容网站维护的页面
  • 个人网站代码模板浙江手机版建站系统信息
  • 网站建设前期规划双语版网站案例