如何在Spring Boot应用程序中包含Spring Security

时间:2018-12-07 05:20:09

标签: maven spring-boot spring-security thymeleaf

我正在使用Spring Boot应用程序。开发应用程序之后,我们现在尝试在应用程序中包括spring安全性。

我包含了以下代码:

html代码:

<li th:if="${#authorization.expression('!isAuthenticated()')}">
<a th:href="@{/login}" th:text="#{navbar.login.text}" />
                    </li>

Java代码:

package com.devopsbuddy.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {



    private static final String[] PUBLIC_MATCHERS = {
            "/webjars/**",
            "/css/**",
            "/js/**",
            "/images/**",
            "/",
            "/about/**",
            "/contact/**",
            "/error/**/*"           
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {



        http
                .authorizeRequests()
                .antMatchers(PUBLIC_MATCHERS).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/payload")
                .failureUrl("/login?error").permitAll()
                .and()
                .logout().permitAll();
    }


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser("user").password("password")
            .roles("USER");
    }
}

当我尝试点击网址时:

http://localhost:8080/

我在屏幕上收到以下错误:

**36673 [http-nio-8080-exec-2] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][http-nio-8080-exec-2] Exception processing template "user/login": Exception evaluating SpringEL expression: "#authorization.expression('!isAuthenticated()')" (template: "common/navbar" - line 24, col 25)
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#authorization.expression('!isAuthenticated()')" (template: "common/navbar" - line 24, col 25)
    at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:290)
    at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
    at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:125)
...
...

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method expression(java.lang.String) on null context object
    at org.springframework.expression.spel.ast.MethodReference.throwIfNotNullSafe(MethodReference.java:153)
    at org.springframework.expression.spel.ast.MethodReference.getValueRef(MethodReference.java:82)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:67)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:111)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:328)
    at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:263)
    ... 102 common frames omitted

36673 [http-nio-8080-exec-2] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#authorization.expression('!isAuthenticated()')" (template: "common/navbar" - line 24, col 25)] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method expression(java.lang.String) on null context object
    at org.springframework.expression.spel.ast.MethodReference.throwIfNotNullSafe(MethodReference.java:153)
    at org.springframework.expression.spel.ast.MethodReference.getValueRef(MethodReference.java:82)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:67)**

pom.xml

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


<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>2.1.2.RELEASE</version>
        </dependency>

我不熟悉Thymeleaf和Spring安全。所以不知道为什么Spring安全性会失败。

如果我用authorization.expression()注释该行,那么它将起作用。

我已经在分支机构安全性的https://github.com/azaveri7/devopsbuddy上共享了代码。

请告知。

3 个答案:

答案 0 :(得分:0)

请将此视为建议,而不是答案。以前我也经历过,但很难弄清楚。然后我决定通过spring的自动配置。我只使用了这个库-

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

,然后spring提供了登录URL,登录页面,注销URL等。我只写了userdetailsS​​ervice。就我而言,我还编写了一个自定义过滤器。

答案 1 :(得分:0)

我在下面检查用户是否未登录

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

....

    <span sec:authorize="not isAuthenticated()">
         You are not logged in - click <a th:href="@{/login}">login</a>
    </span>
...

答案 2 :(得分:0)

您的pom中的spring安全性是5.0.9,它扩展了spring-boot-starter-parent 2.0.6

但是thymeleaf-extras-springsecurity4 仍然是spring security 4,因此您需要将thymeleaf-extras升级到

const resultMock = new Subject(); // saving Subject in order to emulate service response using it
spyOn(encomendaServiceStub, 'getencomenda').and.returnValue(resultMock);
comp.getencomenda();
resultMock.next(<some_value>); // at this moment your function in the subscribe() will be called.
相关问题