springsecurity常见的case

本文详细介绍了如何在Spring Boot项目中使用Spring Security进行权限管理,包括基本的登录认证、角色权限分配以及从数据库中获取用户信息的方法。通过案例演示了不同角色的权限设置和使用@PreAuthorize注解进行方法级别的权限控制。

首先在pom中引入:

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

为了方便介绍将case1的前两张图片 定义为模块一 和模块二 ;

case1:只能登陆就可以:

@EnableWebSecurity
@Configuration
class  SpringSecurityConfig extends WebSecurityConfigurationAdapter{
        
      @Override  
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("seller");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "images/**");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and().logout().permitAll()
                .and().formLogin();
        http.csrf().disable();
    }
        






}

 

package com.yumin.security;

import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.jws.HandlerChain;

@SpringBootApplication
@RestController
public class SecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityApplication.class, args);
    }

    @GetMapping("/")
    public  String  index(){
        return "hello , home!";
    }

    @GetMapping("/plc")
    public String  login(){
        return "hello ,plc !";
    }


   
}

 

 

case2:

有指定的角色 ,每个角色有不同的权限 

首先我们添加几个角色:

在模块一改动为:

  @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("BOSS");
        auth.inMemoryAuthentication().withUser("yumin").password("yumin").roles("BOSS");
        auth.inMemoryAuthentication().withUser("yanyuye").password("yanyuye").roles("WORK");
    }

添加了两个BOSS 一个Work

那么我们处理模块二:

写了一个新方法 :

   @PreAuthorize("hasRole('ROLE_BOSS')")
    @GetMapping("/tolk")
    public  String tolk(){
        return "boss is tolking";
    }

这个方法上面写了@PreAuthorize("hasRole('ROLE_BOSS')")

注意:

这个注解"ROLE_BOSS"  ROLE_XXX 是一个前缀

这样的话是不是就可以了?  No  还差一个启动注解

@EnableGlobalMethodSecurity(prePostEnabled = true)

想使用@PreAuthorize("hasRole('Role_Boss')")  或者@PostAuthorize()  必须在该类上面加上@EnableGlobalMethodSecurity(prePostEnable=true)

case:3 

从数据库里面取出数据(模仿拿出数据)

1.首先实现写一个类实现UserDetailsService 


@Component
public class MyUserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Collection<GrantedAuthority> collections = getAuthorities();
        return new User("admin", "admin", true, true, true, true, collections);
    }

    private Collection<GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));
        return authList;

    }
}

然后吧这个类配置到模块一的configuration方法中

  @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("BOSS");
//        auth.inMemoryAuthentication().withUser("yumin").password("yumin").roles("BOSS");
//        auth.inMemoryAuthentication().withUser("yanyuye").password("yanyuye").roles("WORK");
        auth.userDetailsService(myUserService).passwordEncoder(myPasswordEncoder) ;
    }

手写的注销掉就可以了

然后这个地方我们用到的是

Session timeout in Spring Security refers to the amount of time a user's session can remain active without any activity. When a user logs in to a web application, a session is created for that user. The session remains active until the user logs out, or until the session timeout period expires. By default, Spring Security sets the session timeout to 30 minutes. However, this can be configured in the application's configuration file. To change the session timeout value, you need to set the `server.servlet.session.timeout` property in your `application.properties` file. For example, to set the session timeout to 60 minutes, you can add the following line to your `application.properties` file: ``` server.servlet.session.timeout=60m ``` In addition to setting the session timeout, you can also configure Spring Security to handle session expiration. For example, you can redirect the user to a login page or display a custom message when the session expires. To do this, you need to configure the `session-management` element in your Spring Security configuration file. ``` <http> ... <session-management> <concurrency-control max-sessions="1" expired-url="/login?expired=true" /> </session-management> </http> ``` In the above example, the `max-sessions` attribute limits the user to only one session at a time. If the user tries to open a new session, the previous session will be invalidated. The `expired-url` attribute specifies the URL to redirect the user to when the session expires. In this case, the user will be redirected to the login page with a query parameter indicating that the session has expired.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值