1. 程式人生 > >springboot從入門到精通(三)

springboot從入門到精通(三)

per wired www. 分享 autowire leaf cto 通過 generated

再開始第三節之前,先補充一下第二節裏出現的小問題,就是springboot的application.properties,我在文件中添加了server.port=9090這個參數,但是啟動項目後並未生效,檢查了一下原因,是因為未讀取到該文件,這裏可以通過buildpath添加source文件夾解決,如下圖:

技術分享圖片

好了,我們一起開始第三節:

這一節我們來擴展我們的應用程序,在pom文件中添加以下依賴:

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

運行項目,打開之前的頁面地址,發現進入了一個登錄頁面,如下圖:

技術分享圖片

用戶名為user,密碼在eclipse的控制臺可以看到,如下圖:

技術分享圖片

輸入之後登錄成功,就可以正常訪問頁面了。

但這樣肯定不能滿足我們的需求,所以我們需要創建自定義的安全配置,

1、擴展WebSecurityConfigurerAdapter配置類:

package com.dota.herolist.security;

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.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.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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import com.dota.herolist.repository.UserRepository;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
  @Autowired
  private UserRepository userRepository;
  @Override
  protected void configure(HttpSecurity http) throws Exception{
    http.authorizeRequests()
    .antMatchers("/heroList/**").hasRole("player")//查看該路徑必須擁有player角色
    .and()
    .formLogin().loginPage("/login").failureUrl("/login?error=true");

  }
  @Bean
  @Override
  public UserDetailsService userDetailsService() {
    UserDetails user =
      User.withDefaultPasswordEncoder()
      .username("user")
      .password("password")
      .roles("player")
      .build();

      return new In MemoryUserDetailsManager(user);
  }
}

2、定義User實體的JPA實體

package com.dota.herolist.entity;

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

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

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

@Entity
public class User implements UserDetails{
private static final long serialVersionUID = 1L;
@Id
private String username;
private String password;

public User(String username,String password){
this.username = username;
this.password = password;
}

public User() {
// TODO Auto-generated constructor stub
}

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> list=new ArrayList<SimpleGrantedAuthority>();
list.add(new SimpleGrantedAuthority("player"));
return list;
}

@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}

3、添加controller層:

package com.dota.herolist.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class LoginController {
@RequestMapping(value="/login",method=RequestMethod.GET)
public String login(Model model){
return "login";
}
}

4、添加html頁面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>dota hero </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>

啟動項目,

技術分享圖片

輸入user,password登錄成功。下一章我們將展示如何連接數據庫進行安全認證。

springboot從入門到精通(三)