Spring Security with Spring Boot 2.0:使用Servlet堆栈的简单身份验证

Spring安全性是一个很好的框架,可节省开发人员的大量时间和精力。 此外,它还具有足够的灵活性,可以自定义并满足您的需求。 随着spring的发展,spring安全性也使得在项目中设置安全性变得更加容易和自举。

Spring Boot 2.0已经存在 ,我们将在我们的安全项目中利用它。 在此项目中,我们旨在创建一个尽可能简单的安全支持项目。 首先,我们将创建一个简单的spring boot 2.0项目。

我们可以使用spring SPRING INITIALIZR应用程序。

该项目的最终结果将是创建一个带有gradle的spring boot 2项目。

buildscript {
	ext {
		springBootVersion = '2.0.1.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.gkatzioura.security'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
	mavenCentral()
}


dependencies {
	compile('org.springframework.boot:spring-boot-starter-security')
        compile('org.springframework.boot:spring-boot-starter-web')
	testCompile('org.springframework.boot:spring-boot-starter-test')
	testCompile('org.springframework.security:spring-security-test')
}

现在请注意,使用Spring Boot 2有两个堆栈。 Servlet堆栈或WebFlux反应式堆栈。 在本教程中,我们将使用servlet堆栈。 我们将在另一个教程中介绍WebFlux。

让我们添加第一个控制器。

package com.gkatzioura.security.simple.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

    @GetMapping("/hello")
    public ResponseEntity<String> hello(String name) {

        return new ResponseEntity<>("Hello "+name, HttpStatus.OK);
    }

}

如果尝试访问端点http:// localhost:8080 / hello?name = john,我们将看到一个登录屏幕。 因此,将安全性依赖项包含在我们的项目中会自动保护我们的端点并使用密码配置用户。 为了检索密码,您可以在登录屏幕上检查。 用户名将为“ user”,密码将为spring自动生成的密码。

当然,使用自动生成的密码是不够的,因此我们将提供我们选择的用户名和密码。

在application.yaml文件上设置用户名和密码的方法之一

spring:
  security:
    user:
      name: test-user
      password: test-password

现在,将密码放在文件系统中(尤其是在未加密时)不是一个好习惯,更不要​​说将其上传到版本控制中,因为application.yaml是源文件。 任何有权访问二进制文件的人都可以检索用户名和密码

因此,您可以通过使用环境变量来设置它们,而不是将这些敏感信息放入application.yaml文件中。

所以你的环境变量是

SPRING_SECURITY_USER_NAME=test-user
SPRING_SECURITY_USER_PASSWORD=test-password

综上所述,这是增加项目安全性的最简单,最快的方法。 在下一个博客中,我们将使用WebFlux反应堆进行相同的操作。

翻译自: https://www.javacodegeeks.com/2018/05/spring-security-with-spring-boot-2-0-simple-authentication-using-the-servlet-stack.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值