使用SpringBootSecurityStarter加密REST服務
Spring Initializrofollow,noindex"> http://start.spring.io/ 是引導Spring Boot專案的絕佳工具。我們使用它建立我們的案例:
-
啟動Spring Initializr並選擇以下內容
-
選擇
com.samples.springboot
為組 -
選擇
student-services
為神器 -
選擇以下依賴項
- 捲筒紙
-
選擇
- 單擊“生成專案”。
- 將專案匯入Eclipse。
- 如果您想了解屬於該專案的所有檔案,可以訪問此處。
設定簡單的Web應用程式
讓我們快速設定一個簡單的Web應用程式,以確保使用Spring Security。我們將建立一個Controller,它將重定向到歡迎檢視 - 一個簡單的jsp。
JSP支援
我們希望使用JSP作為檢視。Spring Boot Starter Web的預設嵌入式servlet容器是tomcat。要啟用對JSP的支援,我們需要在tomcat-embed-jasper上新增依賴項。
<dependency><font></font> <groupId>org.apache.tomcat.embed</groupId><font></font> <artifactId>tomcat-embed-jasper</artifactId><font></font> <scope>provided</scope><font></font> </dependency><font></font>
新增登入控制器
LoginController將根URL“/”對映到showLoginPage方法。硬編碼名稱將填充到模型中。它返回一個對映到welcome.jsp的檢視名稱“welcome”。
package com.samples.springboot.web.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class LoginController { @RequestMapping(value = "/", method = RequestMethod.GET) public String showLoginPage(ModelMap model) { model.put("name", "samples"); return "welcome"; } }
新增welcome.jsp
welcome.jsp是一個簡單的jsp,帶有歡迎訊息。
<div class="container"> Welcome ${name}!! </div>
配置檢視解析器
歡迎jsp在資料夾src / main / webapp / WEB-INF / jsp /中。我們將在application.properties中配置一個檢視解析器,以將檢視名稱對映到物理jsp
spring.mvc.view.prefix=/WEB-INF/jsp/<font></font> spring.mvc.view.suffix=.jsp<font></font>
執行Web應用程式
將StudentServicesApplication作為java應用程式啟動。以下螢幕截圖顯示了在http:// localhost:8080上啟動的應用程式。
新增簡單REST服務
讓我們也新增一個簡單的REST服務。我們將補充
- 兩個模型物件 - 課程和學生。學生可以註冊多門課程。
- 一個業務服務 - 管理業務邏輯。我們使用的大多數業務邏輯都位於儲存在靜態ArrayList中的硬編碼資料之上。
- 一個休息控制器 - StudentController。公開一個休息服務以檢索學生註冊的課程列表。
模型和業務邏輯
下面的程式碼段顯示了模型物件Course和Student的摘錄。
public class Course { private String id; private String name; private String description; private List<String> steps; }
public class Student { private String id; private String name; private String description; private List<Course> courses; }
StudentService提供了一種public List<Course> retrieveCourses(String studentId)
檢索學生註冊課程的方法。
@Component public class StudentService { private static List<Student> students = new ArrayList<>(); static { // Initialize Data Course course1 = new Course("Course1", "Spring", "10 Steps", Arrays.asList("Learn Maven", "Import Project", "First Example", "Second Example")); Course course2 = new Course("Course2", "Spring MVC", "10 Examples", Arrays.asList("Learn Maven", "Import Project", "First Example", "Second Example")); Student ranga = new Student("Student1", "Ranga Karanam", "Hiker, Programmer and Architect", new ArrayList<>( Arrays.asList(course1, course2))); students.add(ranga); } public Student retrieveStudent(String studentId) { for (Student student : students) { if (student.getId().equals(studentId)) { return student; } } return null; } public List<Course> retrieveCourses(String studentId) { Student student = retrieveStudent(studentId); if (student == null) { return null; } return student.getCourses(); } }
建立REST服務
Rest ServiceStudentController
在URI對映“/ students / {studentId} / courses”中公開了一個簡單的Get服務。它StudentService
是自動連線的。
package com.samples.springboot.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.samples.springboot.model.Course; import com.samples.springboot.service.StudentService; @RestController public class StudentController { @Autowired private StudentService studentService; @GetMapping("/students/{studentId}/courses") public List<Course> retrieveCoursesForStudent(@PathVariable String studentId) { return studentService.retrieveCourses(studentId); } }
執行REST服務
執行休息服務很容易。在您的瀏覽器或您最喜愛的休息客戶端中訪問URL http:// localhost:8080 / students / Student1 / courses。
新增Spring Boot Starter Security
現在讓我們將Spring Boot Starter Security新增為該專案的依賴項。
<dependency><font></font> <groupId>org.springframework.boot</groupId><font></font> <artifactId>spring-boot-starter-security</artifactId><font></font> </dependency><font></font> <font></font>
自動配置
當我們重新啟動應用程式時,我們會在日誌中看到以下語句。
Mapping filter: 'springSecurityFilterChain' to: [/*]<font></font> <font></font> Using default security password: 25e07e82-720d-4109-ba8d-25177c6347e6<font></font> <font></font> Creating filter chain:<font></font> ...<font></font> ...<font></font> <font></font>
所有這些魔力都是因為自動配置:
-
Mapping filter: 'springSecurityFilterChain' to: [/*]
:預設情況下,為應用程式中的所有URL啟用Spring Security。 - 基本身份驗證是預設設定。
-
Using default security password: 25e07e82-720d-4109-ba8d-25177c6347e6
:預設使用者標識是使用者。預設密碼列印在伺服器啟動日誌中。在此示例中,密碼為25e07e82-720d-4109-ba8d-25177c6347e6 - 某些過濾器鏈配置為啟用安全性
執行REST服務
當我們現在在http:// localhost:8080 / students / Student1 / courses執行Rest Service時,它會返回身份驗證失敗。狀態為401,訊息“Bad credentials”。這是因為我們的服務現在受到Spring Security的保護。
{ "timestamp": 1485768623632, "status": 401, "error": "Unauthorized", "message": "Bad credentials", "path": "/students/Student1/courses" }
使用基本身份驗證執行Rest服務
通過搜尋從日誌中獲取密碼Using default security password:
。使用者標識是使用者。使用此組合可使用基本身份驗證執行服務。
執行Web應用程式
當您在瀏覽器中啟動URL http:// localhost:8080時,會彈出一個要求輸入使用者名稱和密碼的彈出視窗。您需要輸入我們為REST服務提供的相同詳細資訊。
通過新增一個簡單的依賴Spring Boot Starter Security,我們開啟了很多魔術。
配置自定義使用者和角色
我們現在配置自定義使用者和角色
- 我們將使用Admin和User兩個角色。管理員角色可以訪問Web應用程式,使用者角色可以訪問執行REST服務。
- 我們將使用憑據admin1 / secret1為Admin角色建立一個使用者
- 我們將使用憑據user1 / secret1為User角色建立一個使用者
package com.samples.springboot.security; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { // Authentication : User --> Roles protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(or g.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance()). withUser("user1") .password("secret1") .roles("USER").and().withUser("admin1").password("secret1") .roles("USER", "ADMIN"); } // Authorization : Role -> Access protected void configure(HttpSecurity http) throws Exception { http.httpBasic().and().authorizeRequests().antMatchers("/students/**") .hasRole("USER").antMatchers("/**").hasRole("ADMIN").and() .csrf().disable().headers().frameOptions().disable(); } }
執行REST服務
現在我們可以使用user1 / secret1組合來執行休息服務。
啟動Web應用程式
我們需要在彈出視窗中使用admin1 / secret1組合來啟動Web應用程式。