Spring Boot 集成Security

1、在pom.xml 添加 Security依赖和thymeleaf依赖

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

 

2、添加SecurityConfig.java  

 

package com.example.demo.session;

import org.springframework.beans.factory.annotation.Autowired;
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.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.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.example.demo.session.user.MyUserDetailsService;

@Configuration
@EnableWebSecurity    //  开启Security
public class SecurityConfig extends WebSecurityConfigurerAdapter {   //继承WebSecurityConfigurerAdapter类
    
       @Autowired
       private MyUserDetailsService myUserDetailsService;
      
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          
            // TODO Auto-generated method stub
            //super.configure(http);
            http
                  .formLogin().loginPage("/demo-sign.html").loginProcessingUrl("/login/form").failureUrl("/login-error").permitAll()  //表单登录,permitAll()表示这个不需要验证 登录页面,登录失败页面
                  .and()
                  .authorizeRequests().anyRequest().authenticated()                  
                  .and()
                  .csrf().disable();            
      }
      
      
      
      
//      @Override
//      protected void configure(AuthenticationManagerBuilder auth) throws Exception{
//                  
//                  auth
//                  .inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
//                        .withUser("admin").password("123456").roles("USER")
//                        .and()
//                        .withUser("test").password("test123").roles("ADMIN");
//      }
      
      
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 调用  myUserDetailsService 类进行用户验证
          auth.userDetailsService(myUserDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());
      }

     @Bean
     public PasswordEncoder passwordEncoder() {
             return new BCryptPasswordEncoder();
     }

}
 

3、创建MyUserDetailsService类,获取用户信息已经用户权限

 

package com.example.demo.session.user;

import java.util.ArrayList;
import java.util.List;

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.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Service
public class MyUserDetailsService implements UserDetailsService{

    @Override
    public UserDetails loadUserByUsername(String arg0) throws UsernameNotFoundException {
//        SysUser sysUser = userService.getUserByName(username);
//        if (null == sysUser) {
//              throw new UsernameNotFoundException(username);
//         }
         List<SimpleGrantedAuthority> authorities = new ArrayList<>();
         authorities.add(new SimpleGrantedAuthority("001"));
        return new User("admin", "123", authorities);
    }

}
 

 

4、在resource的static目录下添加登录页面

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

    <body>
      <form  class="form-signin" action="/login/form" method="post">
              <h2 class="form-signin-heading">用户登录</h2>
            <table>
                  <tr>
                        <td>用户名:</td>
                        <td><input type="text" name="username"  class="form-control"  placeholder="请输入用户名"/></td>
                  </tr>
                        <tr>
                        <td>密码:</td>
                        <td><input type="password" name="password"  class="form-control" placeholder="请输入密码" /></td>
                  </tr>
                  <tr>
                  
                        <td colspan="2">
                              <button type="submit"  class="btn btn-lg btn-primary btn-block" >登录</button>
                        </td>
                  </tr>
            </table>
      </form>

    </body>
</html>

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值