1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > [SpringSecurity]web权限方案_用户授权_基于权限访问控制_基于角色访问控制_hasAuthor

[SpringSecurity]web权限方案_用户授权_基于权限访问控制_基于角色访问控制_hasAuthor

时间:2020-10-30 23:40:57

相关推荐

[SpringSecurity]web权限方案_用户授权_基于权限访问控制_基于角色访问控制_hasAuthor

基于角色或权限进行访问控制

hasAuthority 方法

如果当前的主体具有指定的权限,则返回 true,否则返回 false

在配置类设置当前访问地址有哪些

@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin() //自定义自己编写的登陆页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问路径.defaultSuccessUrl("/test/index").permitAll() //登陆成功之后,跳转路径.and().authorizeRequests().antMatchers("/","/test/hello","/user/login").permitAll() //设置哪些路径可以直接访问,不需要认证//当前登陆用户,只有具有admin权限才可以访问这个路径.antMatchers("/test/index").hasAuthority("admins").anyRequest().authenticated().and().csrf().disable(); //关闭csrf防护}

在UserDetailsService,把返回User对象设置权限

@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//调用userMapper方法,根据用户名查询数据库QueryWrapper<Users> wrapper = new QueryWrapper<>();//where username = ?wrapper.eq("username",username);Users users = usersMapper.selectOne(wrapper);//判断if (users==null)//数据库没有用户名,认证失败{throw new UsernameNotFoundException("用户名不存在!");}List<GrantedAuthority> auths = maSeparatedStringToAuthorityList("admins");return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);}

测试

没有访问权限 403

hasAnyAuthority 方法

如果当前的主体有任何提供的“角色”的话,返回true.

@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin() //自定义自己编写的登陆页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问路径.defaultSuccessUrl("/test/index").permitAll() //登陆成功之后,跳转路径.and().authorizeRequests().antMatchers("/","/test/hello","/user/login").permitAll() //设置哪些路径可以直接访问,不需要认证////当前登陆用户,只有具有admin权限才可以访问这个路径//.antMatchers("/test/index").hasAuthority("admins").antMatchers("/test/index").hasAnyAuthority("admins”,“manager").anyRequest().authenticated().and().csrf().disable(); //关闭csrf防护}

hasRole 方法

如果用户具备给定角色就允许访问,否则出现 403。

如果当前主体具有指定的角色,则返回 true。

从源码中我们可以看出,前面会自动加个ROLE_

hasAnyRole

表示用户具备任何一个条件都可以访问。

[SpringSecurity]web权限方案_用户授权_基于权限访问控制_基于角色访问控制_hasAuthority和hasAnyAuthority_hasRole和hasAnyRole

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。