1. 程式人生 > >SpringBoot 下 SpringSecurity 入門搭建

SpringBoot 下 SpringSecurity 入門搭建

提示:僅供自己學習參考(開發環境maven3.9+jdk1.7+eclipseMar4.5.2)

1、目錄結構:


2、原始碼:

(1)Springboot001Application 類

package com.ljh.springboot001;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Springboot001Application {


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

(2)WebMvcConfig 類繼承WebMvcConfigurerAdapter(spring-webmvc-4.1.16.RELEASE.jar的)

package com.ljh.springboot001.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}

}

(3)WebSecurityConfig 類繼承WebSecurityConfigurerAdapter(spring-security-config-3.2.7.RELEASE.jar的)

package com.ljh.springboot001.config;

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.UserDetailsService;

import com.ljh.springboot001.security.CustomUserService;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{


@Bean
UserDetailsService customUserService(){
System.out.println("userservice ........................");
return new CustomUserService();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
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();
}
// .defaultSuccessUrl("/home")

}


(4)SysUserRepository介面繼承JpaRepository(spring-data-jpa-xxx.jar的)

package com.ljh.springboot001.dao;
 
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


import com.ljh.springboot001.domain.SysUser;


@Repository
public interface SysUserRepository extends JpaRepository<SysUser, Long>{  
     
SysUser findByUsername(String username);
}  

(5)Msg 類

package com.ljh.springboot001.domain;


public class Msg {


private String title;
private String content;
private String etraInfo;
public Msg(String title, String content, String etraInfo) {
super();
this.title = title;
this.content = content;
this.etraInfo = etraInfo;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getEtraInfo() {
return etraInfo;
}
public void setEtraInfo(String etraInfo) {
this.etraInfo = etraInfo;
}

}

(6)SysRole 類

package com.ljh.springboot001.domain;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;


@Entity
public class SysRole {//角色 即 許可權
@Id
@GeneratedValue
private Long id;

private String name;
    
public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public Long getId() {
return id;
}


public void setId(Long id) {
this.id = id;
}

}


(7)SysUser  類實現UserDetails   介面(spring-security-core-xxx.jar)

package com.ljh.springboot001.domain;


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

import javax.annotation.Generated;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;


import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;


@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;
}

public List<SysRole> getRoles() {
return roles;
}

public Long getId() {
return id;
}


public void setId(Long id) {
this.id = id;
}


public void setUsername(String username) {
this.username = username;
}


public void setPassword(String password) {
this.password = password;
}


public void setRoles(List<SysRole> roles) {
this.roles = roles;
}




@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;
}


}


(8)CustomUserService 類實現UserDetailsService介面(spring-security-core-xxx.jar)

package com.ljh.springboot001.security;


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;


import com.ljh.springboot001.dao.SysUserRepository;
import com.ljh.springboot001.domain.SysUser;


public class CustomUserService implements UserDetailsService{
@Autowired
SysUserRepository sysUserRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("loadUserByUsername......................");
SysUser user  = sysUserRepository.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException("使用者名稱不存在");
}
return user;
}


}

(9)HomeController 類

package com.ljh.springboot001.web;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


import com.ljh.springboot001.domain.Msg;


@Controller
public class HomeController {


@RequestMapping("/")
public String index(Model model){
Msg msg = new Msg("測試標題","測試內容","額外資訊,只對管理員 lZ示 ");
model.addAttribute("msg",msg);
return "home";
}
}


(10)bootstrap檔案


(11)thymeleaf模板檔案


(12)springboot核心配置檔案(application.properties)

server.port=9000
#spring.datasource.driverClassName=com.mysql.jdbc.Driver
#spring.datasource.url=jdbc\:mysql\:\localhost:3306\test?useUnicode=true&&characterEncoding=utf-8
#spring.datasource.username=root
#spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.password=123456
spring.datasource.username=root
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

logging.level.org.springframework.security=INFO
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html  
#spring.thymeleaf.mode=HTML5  
#spring.thymeleaf.encoding=UTF-8;charset=<encoding> is added 
#spring.thymeleaf.content-type=text/html  
spring.thymeleaf.cache=true
  
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
server.tomcat.uri-encoding=utf-8
#spring.mvc.view.prefix=/templates/
#spring.mvc.view.suffix=.html
#記憶體中的預設使用者賬號
security.user.name=ljh
#記憶體中的預設密碼
security.user。password=ljh
(13)data.sql檔案
 
insert into SYS_USER(id ,username,password) values (1,'ljh','ljh');
insert into SYS_USER(id ,username,password) values (2,'sdd','sdd');
insert into SYS_ROLE(id ,name) values (1,'ROLE_ADMIN');
insert into SYS_ROLE(id ,name) values (2,'ROLE_USER');
insert into SYS_USER_ROLES(SYS_USER_ID ,ROLES_ID) values (1,1);
insert into SYS_USER_ROLES(SYS_USER_ID ,ROLES_ID) values (2,2);

(14)home.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta content="text/html;charset=UTF-8"/>
<title sec:authentication="name"></title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"/>
<style type="text/css">
body{
padding-top:50px;
}
.starter-template{
padding:40px 15px;
text-align: center;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class = "navbar-header">
<a class = "navbar-brand" href = "#">Spring security demo</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class = "nav navbar-nav">
<li><a th:href="@{/}">首頁</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="starter-template">
<h1 th:text="${msg.title}"></h1>
<p class="bg-primary" th:text="${msg.content}"></p>
<div sec:authorize="hasRole('ROLE_ADMIN')"> 
<p class="bg-info" th:text="${msg.etraInfo}"></p>
</div>
<div sec:authorize="hasRole('ROLE_USER')"> 
<p class="bg-info"> 無更多資訊顯示</p>
</div>
<form th:action="@{/logout}" method="post">
<input type="submit" class="btn btn-primary" value="exit"/>
</form>
</div>
</div>
</body>
</html>
(15)login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout">
<head>
<meta content="text/html;charset=UTF-8"></meta>
<title>login  page </title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"/>
<style type="text/css">
body{
padding-top:50px;
}
.starter-template{
padding:40px 15px;
text-align: center;
}
</style>


</head>


<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class = "navbar-header">
<a class = "navbar-brand"  href = "#">Spring security demo</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class = "nav navbar-nav">
<li><a th:href="@{/}">首頁</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="starter-template">
<p th:if="${param.logout}" class="bg-warning">成功登出</p>
<p th:if="${param.error}" class="bg-danger">有錯誤,重試1233</p>
</div>
<h2>請登入</h2>
<form name = "form" th:action="@{/login}" action="/login" method="post">
<div class="form-group">
<label for="username">賬號</label>
<input type="text" class="form-control" name="username" value="" placeholder="username"/>
</div> 
<div class="form-group">
<label for="password">mima</label>
<input type="password" class="form-control" name="password" value="" placeholder="password"/>
</div> 
<input type="submit" id="login" value="Login"  class="btn btn-primary"/>
</form>
</div>
</body>
</html>


(16)pom.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>


<groupId>com.ljh</groupId>
<artifactId>springboot001</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>


<name>springboot001</name>
<description>Demo project for Spring Boot</description>


<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>


<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>


<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
    <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
<!-- <dependency> -->
<!--    <groupId>javax.persistence</groupId> -->
<!--    <artifactId>persistence-api</artifactId> -->
<!--    <version>1.0</version> -->
<!-- </dependency> -->
<dependency>
  <groupId>org.hibernate.javax.persistence</groupId>
  <artifactId>hibernate-jpa-2.0-api</artifactId>
  <version>1.0.1.Final</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
   <version>1.5.6.RELEASE</version>
</dependency>
   
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
   <version>1.5.6.RELEASE</version>
</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>
       <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
<dependency>
   <groupId>org.thymeleaf.extras</groupId>
   <artifactId>thymeleaf-extras-springsecurity4</artifactId>
   <version>2.1.3.RELEASE</version>
</dependency>
<dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-thymeleaf</artifactId>  
</dependency>  
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/servlet-api -->
<dependency>
   <groupId>org.apache.tomcat</groupId>
   <artifactId>servlet-api</artifactId>
   <version>6.0.39</version>
</dependency>

</dependencies>


<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>




</project>


相應的錯誤解決辦法看下篇:http://blog.csdn.net/lijiaheng525/article/details/76916732