Step3-基于Spring Security 权限管理Case实操

常见Case实现

Case1.只要能登录即可

在Step2的代码基础上进行拓展

这里写图片描述

这里写图片描述

这里写图片描述

代码部分:

package com.mmall.demo;

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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by mac on 2017/12/27.
 */
@Configuration
@EnableWebSecurity  //打开Web支持

//extends 实现类
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {//此方法设置哪些请求会被拦截,以及一些请求应该怎样处理
        http.authorizeRequests()
                .antMatchers("/").permitAll()//项目主路径可以随意访问
                .anyRequest().authenticated()//其他请求都是受限制的
                .and() //允许
                .logout().permitAll()//允许注销,随意访问
                .and()
                .formLogin();//允许表单登录
        http.csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception{
        web.ignoring().antMatchers("/js/**","/css/**","/images/**");//设置js,css,images都不去做权限拦截
    }
}

运行项目。此时,如果我们打开浏览器,输入http://localhost:8080/hello,则会显示让你输入用户名和密码,我们输入定义好的用户名admin,密码123456则可以进入。

输入http://localhost:8080/login?logout,则可以退出登录。

Case2.有指定的角色,每个角色有指定的权限

SpringSecurityConfig类中,添加一个USER角色

   @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("zhangsan").password("zhangsan").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("demo").password("demo").roles("USER");
    }

DemoApplication类中,添加一个方法

@PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping("/roleAuth")  //设置访问路径
    public String role(){
        return "admin auth";
    }

打开浏览器,输入http://localhost:8080/roleAuth,需要进行登录。
我们输入用户demo,密码demo则提示登录错误,使用用户名admin,123456登录则正确

使用数据库管理用户Case

新建MyUserService类

package com.mmall.demo;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * Created by mac on 2017/12/27.
 */
@Component
public class MyUserService implements UserDetailsService{
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return null;
    }
}

修改SpringSecurityConfig类

package com.mmall.demo;

import org.springframework.beans.factory.annotation.Autowired;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by mac on 2017/12/27.
 */
@Configuration
@EnableWebSecurity  //打开Web支持

//extends 实现类
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private MyUserService myUserService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
//        auth.inMemoryAuthentication().withUser("zhangsan").password("zhangsan").roles("ADMIN");
//        auth.inMemoryAuthentication().withUser("demo").password("demo").roles("USER");

        auth.userDetailsService(myUserService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {//此方法设置哪些请求会被拦截,以及一些请求应该怎样处理
        http.authorizeRequests()
                .antMatchers("/").permitAll()//项目主路径可以随意访问
                .anyRequest().authenticated()//其他请求都是受限制的
                .and() //允许
                .logout().permitAll()//允许注销,随意访问
                .and()
                .formLogin();//允许表单登录
        http.csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception{
        web.ignoring().antMatchers("/js/**","/css/**","/images/**");//设置js,css,images都不去做权限拦截
    }
}

新建MyPasswordEncoder类进行用户名密码加密匹配

package com.mmall.demo;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Created by mac on 2017/12/27.
 */
public class MyPasswordEncoder implements PasswordEncoder{

    private  final static String SALT = "123456";

    @Override
    public String encode(CharSequence charSequence) {//加密方法
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();

        return encoder.encodePassword(charSequence.toString(),SALT);
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {//匹配方法
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        return encoder.isPasswordValid(s,charSequence.toString(),SALT);
    }
}

修改SpringSecurityConfig类

   @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
//        auth.inMemoryAuthentication().withUser("zhangsan").password("zhangsan").roles("ADMIN");
//        auth.inMemoryAuthentication().withUser("demo").password("demo").roles("USER");

        auth.userDetailsService(myUserService).passwordEncoder(new MyPasswordEncoder());
        auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(new MyPasswordEncoder());
    }

修改DemoApplication类

package com.mmall.demo;

import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/*
<mirrors>
  <mirror>
    <id>alimaven</id>
    <name>aliyun maven</name>
    <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
    <mirrorOf>central</mirrorOf>
   </mirror>
</mirrors>
*/
@SpringBootApplication
@RestController
@EnableAutoConfiguration  //自动配置
@EnableGlobalMethodSecurity(prePostEnabled = true)

public class DemoApplication {


    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
    }

    @RequestMapping("/")  //设置访问路径
    public String home(){
        return "hello spring boot";
    }

    @RequestMapping("/hello")  //设置访问路径
    public String hello(){
        return "hello world";
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostAuthorize("hasRole('')")
    public String role(){
        return "hello roleAuth";
    }

    @PreAuthorize("#id<10 and principal.username.equals(#username) and #user.username.equals('abc')")
    @PostAuthorize("returnObject%2==0")
    @PreFilter("")
    @PostFilter("") //对集合类参数或其返回值进行过滤
    @RequestMapping("/test")  //设置访问路径
    public Integer test(Integer id, String username, BIConversion.User user){
        return id;
    }

    @PreFilter("returnObject%2==0")
    @PostFilter("") //对集合类参数或其返回值进行过滤
    @RequestMapping("/test2")  //设置访问路径
    public List<Integer> test2(List<Integer> idList){

        return idList;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值