Spring Boot Spring Security Demo
Spring Boot Spring Security Demo
慕容若冰 发表于1年前
Spring Boot Spring Security Demo
  • 发表于 1年前
  • 阅读 102
  • 收藏 3
  • 点赞 0
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

  1. 新建Spring Boot项目,依赖为JPA,Security,Thymeleaf并tian添加MySQL驱动和Thymeleaf的Spring Security支持
  2. <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>5.1.2</version>
    </dependency>
    
    <dependency>
       <groupId>org.thymeleaf.extras</groupId>
       <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>
  3. application.properties配置如下
  4. spring.datasource.url = jdbc:mysql://localhost:3306/jpa
    spring.datasource.username = root
    spring.datasource.password =
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true
    spring.jackson.serialization.indent_output=true
    
    logging.level.org.springframework.security=INFO
    spring.thymeleaf.cache=fals
  5. 用户和角色类
    1. /**
       * 用户类
       * Created by Administrator on 2016/12/8.
       */
      @Entity
      public class SysUser implements UserDetails {
      
          private static final long serialVersionUID = 1L;
      
          @Id
          @GeneratedValue
          private Long id;
      
          private String username;
      
          private String password;
      
          //配置用户与角色多对多关系
          @ManyToMany(cascade = {CascadeType.REFRESH}, fetch = FetchType.EAGER)
          private List<SysRole> roles;
      
          //将用户的角色作为权限
          @Override
          public Collection<? extends GrantedAuthority> getAuthorities() {
              List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
              List<SysRole> roles = this.getRoles();
              for (SysRole role : roles) {
                  auths.add(new SimpleGrantedAuthority(role.getName()));
              }
              return auths;
          }
      
          @Override
          public boolean isAccountNonExpired() {
              return true;
          }
      
          @Override
          public boolean isAccountNonLocked() {
              return true;
          }
      
          @Override
          public boolean isCredentialsNonExpired() {
              return true;
          }
      
          @Override
          public boolean isEnabled() {
              return true;
          }
  6. 数据访问
  7. package com.spingsecurity.dao;
    
    import com.spingsecurity.entity.SysUser;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    /**
     * Created by Administrator on 2016/12/8.
     */
    public interface SysUserRepository extends JpaRepository<SysUser, Long> {
    
        SysUser findByUsername(String username);
    }
  8. 自定义UserDetailsService
  9. package com.spingsecurity.security;
    
    import com.spingsecurity.dao.SysUserRepository;
    import com.spingsecurity.entity.SysUser;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    
    /**
     * Created by Administrator on 2016/12/8.
     */
    public class CustomUserService implements UserDetailsService {
    
        @Autowired
        SysUserRepository userRepository;
    
        //重写loadUserByUsername方法获得用户
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            SysUser user = userRepository.findByUsername(username);
            if (user == null) {
                throw new UsernameNotFoundException("用户名不存在");
            }
            return user;
        }
    }
  10. Spring MVC配置
  11. package com.spingsecurity.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    /**访问/login转向login.html页面
     * Created by Administrator on 2016/12/8.
     */
    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/login").setViewName("login");
        }
    }
  12. Spring Security 配置
  13. package com.spingsecurity.config;
    
    import com.spingsecurity.security.CustomUserService;
    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.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    
    /**
     * Created by Administrator on 2016/12/8.
     */
    @Configuration
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        //注册CustomUserService的Bean
        @Bean
        UserDetailsService customUserService() {
            return new CustomUserService();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //添加自定义的user detail service认证
            auth.userDetailsService(customUserService());
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .anyRequest().authenticated()//所有请求需要认证才能访问
                    .and()
                    .formLogin()//定制登陆行为
                        .loginPage("/login")
                        .failureUrl("/login?error")
                        .permitAll()//登录页面可任意访问
                    .and()
                    .logout().permitAll();//定制注销行为,注销请求可任意访问
        }
    }
  14. 控制器
  15. package com.spingsecurity.web;
    
    import com.spingsecurity.entity.Msg;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * Created by Administrator on 2016/12/8.
     */
    @Controller
    public class HomeController {
    
        @RequestMapping("/")
        public String index(Model model) {
            Msg msg = new Msg("测试标题", "测试内容", "额外信息,只对管理员显示");
            model.addAttribute("msg", msg);
            return "home";
        }
    }
  16. 运行,访问http://localhost:8080,自动跳转http://localhost:8080/login
  17. 源码:https://git.oschina.net/NeedLoser/Spring-Boot.git
共有 人打赏支持
粉丝 0
博文 43
码字总数 9774
×
慕容若冰
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: