首页 > 技术文章 > 初入spring boot security

cxca 2018-03-23 17:13 原文

security的依赖

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

配置一下application.properties

logging.level.org.org.springframework.security=INFO
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

 

创建一个SysUser(用户类),实现UserDetails类,重写里面的方法。

注意属性名字只能是username和password.

package com.example.demo.entity;

import javax.persistence.*;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;

@Entity
public class SysUser implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }


    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

然后写一个service和数据层

package com.example.demo.service;

import com.example.demo.Repository.SysUserRepository;
import com.example.demo.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;
import org.springframework.stereotype.Service;




@Service
public class UserService implements UserDetailsService {
    @Autowired
    SysUserRepository sysUserRepository;

    @Override
    public UserDetails loadUserByUsername(String username){
        SysUser user = sysUserRepository.findByUsername(username);
        if (user == null) {
            System.out.println("用户名不存在");
            throw new UsernameNotFoundException("用户名不存在");
        }
        System.out.println("登录成功");
        return user;
    }

}
package com.example.demo.Repository;

import com.example.demo.entity.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface SysUserRepository extends JpaRepository<SysUser, Long> {

    SysUser findByUsername(String username);
}

写一个WebSecurityConfig

package com.example.demo.config;

import com.example.demo.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
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.UserDetailsService;


@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {//扩展Spring Security配置需继承WebSecurityConfigurerAdapter


@Bean
UserDetailsService userService(){//注册userService的Bean
return new UserService();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService());
//.passwordEncoder(new Md5PasswordEncoder());//添加我们自定义的user detail service认证,密码MD5加密
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").permitAll()//spring security对路径不拦截
.anyRequest().authenticated()//所有请求需要认证即登录后才能访问
.and()
.formLogin()
.loginPage("/login")//登陆页面的访问路径
.defaultSuccessUrl("/index")//登录成功后路径
.failureUrl("/error");//错误页面
}

}

三个页面

写跳转页面的方法

这里注意 WebSecurityConfig里面已经配置好了跳转错误页面的属性 failureUrl("/error"),可以直接跳到error页面,如果写成 failureUrl("/errors")则会进我们自己写的error方法,然后跳转到error页面。

前端login页面代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<form th:action="@{/login}" method="post">
    <input name="username" value="帐号"/>
    <input name="password" value="密码"/>
    <input type="submit" value="登录"/>
</form>

<!-- Javascript -->
<script src="../static/js/jquery-1.12.3.min.js" th:src="@{/js/jquery-1.12.3.min.js}"></script>
</body>
</html>

 数据库写一条用户数据,就可以开始登录了。

最后注意: 前端页面标签记得闭合,spring boot 版本1.5.8

推荐阅读