I am trying to use GitLab OAuth2 with Spring Boot, but I am continuously getting:
redirected uri is invalid
I already registered the app in GitLab.
Here is my application.yml
security:
oauth2:
client:
clientId: CLIENT_ID
clientSecret: CLIENT_SECRET
userAuthorizationUri: https://gitlab.your-domain.com/oauth/authorize
accessTokenUri: https://gitlab.your-domain.com/oauth/token
registered-redirect-uri:
#- http://localhost:8080/login/oauth2/code/gitlab
- http://localhost:8080
tokenName: oauth_token
authenticationScheme: query
clientAuthenticationScheme: form
resource:
userInfoUri: https://gitlab.your-domain.com/api/v4/user
and a simple Spring REST class:
#SpringBootApplication
#EnableOAuth2Sso
#RestController
public class DemoApplication extends WebSecurityConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#RequestMapping("/user")
public Principal user(Principal principal) {
return principal;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**", "/webjars/**", "/error**").permitAll()
.anyRequest().authenticated()
.and()
.logout()
.logoutSuccessUrl("/")
.permitAll();
}
}
Finally the index.html file:
<body>
<h1>Demo</h1>
<div class="container unauthenticated">
With GitLab: click here
</div>
<div class="container authenticated" style="display: none">
Logged in as: <span id="user"></span>
<div>
<button onClick="logout()" class="btn btn-primary">Logout</button>
</div>
</div>
<script type="text/javascript">
$.get("/user", function(data) {
$("#user").html(data.userAuthentication.details.name);
$(".unauthenticated").hide()
$(".authenticated").show()
});
var logout = function() {
$.post("/logout", function() {
$("#user").html('');
$(".unauthenticated").show();
$(".authenticated").hide();
})
return true;
}
</script>
</body>
I am able to login to GitLab, and authorization is also done successfully, finally when it came to redirecting to the base URL:
http://localhost:8080
its saying the redirect URL is not valid.
Here is my 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.learning</groupId>
<artifactId>spring-oauth-gitlab-demo-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<!-- <version>2.1.1</version> -->
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<!-- <version>3.2.0</version> -->
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I was getting the same error in Gitlab and I fixed it by changing http://localhost:5000 to http://localhost:5000/!!
Related
I am quite new to Spring Security and OAuth2 SSO in particular.
I am currently trying to test and learn with this sample Spring Boot OAuth2 tutorial:
https://spring.io/guides/tutorials/spring-boot-oauth2/
I can sign in using similar application.yml settings like this:
security:
oauth2:
client:
clientId: 233668646673605
clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
accessTokenUri: https://graph.facebook.com/oauth/access_token
userAuthorizationUri: https://www.facebook.com/dialog/oauth
tokenName: oauth_token
authenticationScheme: query
clientAuthenticationScheme: form
resource:
userInfoUri: https://graph.facebook.com/me
Here is my 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sao.social.apps</groupId>
<artifactId>SocialApplication</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SocialApplication</name>
<description>OAuth2 Login With Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>js-cookie</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Here is the main class that also has OAuth2SSO enabled as as well as security and rest controller:
#SpringBootApplication
#EnableOAuth2Sso
#RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {
#RequestMapping("/user")
public Principal user(Principal principal) {
return principal;
}
#Override
protected void configure(HttpSecurity httpSec) throws Exception{
httpSec
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**", "/webjars/**", "/error**")
.permitAll()
.anyRequest()
.authenticated()
.and().logout().logoutSuccessUrl("/").permitAll()
.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
public static void main(String[] args) {
SpringApplication.run(SocialApplication.class, args);
}
}
And finally here is the view: index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Demo</title>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width"/>
<base href="/"/>
<link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css"/>
<script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script>
<script type="text/javascript" src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Login</h1>
<div class="container unauthenticated">
With Facebook: click here
</div>
<div class="container authenticated" style="display:none">
Logged in as: <span id="user"></span>
</div>
</div>
<script type="text/javascript">
$.get("/user", function(data) {
$("#user").html(data.userAuthentication.details.name);
$(".unauthenticated").hide();
$(".authenticated").show();
});
</script>
</body>
</html>
My main challenge is that I can login with Facebook(The Authorization Server in this case) but then when I am redirected to localhost:8080/login I always receive 401 unauthorized error from spring instead of showing me the name of the user successfully authenticated and logged in as expected in the view-index.html. Is there something else I need to set up on Facebook or am I missing something on Spring?
Thank you!
Make sure that the package of the SocialApplication class is at the same level as the other packages, it is possible that the #SpringBootApplication annotation of your main class is not scanning its components.
This was a solution for me.
I am following this tutorial too and am having the same issue. After updating to java 11 the problem disappeared and the "loggend in as" div showed.
I have a Spring MVC project with Thymeleaf and in memory authentication.
In my html I want to display the current user that is logged in and diplay the logout button only when somebody is logged in.
Here is a simple html that should display the username, but is always displays Bob and a text that should only be displayed when somebody is logged in, but it's always displayed.
Any idea what I'm doing wrong?
Here is my 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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>info.climbinggyms</groupId>
<artifactId>main</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>main</name>
<description>website with an overview of the existing climbing gyms</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
layout:decorator="layout/root_layout"
lang="en">
<head>
<title>My Climbing Gyms</title>
</head>
<body>
<div layout:fragment="page-content">
<div class="container">
<section>
<br>
<br>
<br>
<h1>My Climbing Gyms</h1>
<p>Welcome to my climbing gyms</p>
<p>This is still under construction, this site only contains dummy data</p>
<div sec:authorize="isAuthenticated()">
This content is only shown to authenticated users.
</div>
<span sec:authentication="name">Bob</span>
</section>
</div>
</div>
</body>
</html>
and my security configuration:
package info.climbinggyms.main;
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.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 {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/admin/**").hasAnyRole("ADMIN","USER")
.and()
.csrf().disable().headers().frameOptions().disable()
.and()
.formLogin()
.and()
.logout();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("bleau83").password("{noop}bleau83").roles("ADMIN")
.and()
.withUser("user").password("{noop}user").roles("USER");
}
}
I updated my thymeleaf security to springsecurity5 and now it is working
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
I've had similar problem, my implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5' was missing from build.gradle altogether.
Yes, You need update to springsecurity5
thymeleaf-extras-springsecurity5
I try to use Spring formtags. I have a running Spring boot application.
I have a hello.jsp like this, which doesn't contain any formtags:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Hello
</body>
</html>
When calling my controller which resolves the view it displays "Hello" as expected.
When adding
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
on top and calling the controller -> all content is shown, the complete source of the page. It seems the taglib is not recognized.
In my dependencies I have (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.solvapps</groupId>
<artifactId>springboottests</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboottests</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.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.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.faces/jsf-api -->
<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My MVC configuration:
#Configuration
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
* Update *
In the console of tomcat I get the following error:
2019-01-31 12:47:40.988 ERROR 13952 --- [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
[Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: org.springframework.http.MediaType.isPresentIn(Ljava/util/Collection;)Z] with root cause
java.lang.NoSuchMethodError: org.springframework.http.MediaType.isPresentIn(Ljava/util/Collection;)Z
What is missing here ? Any help ?
I've been upgrading my app to use spring boot 2 and my views have not been rendering correctly. They content that should be hidden with the is no longer working. My methods and pages are still secured properly so it seems to be an issue with rendering the page. Also, isAuthenticated and isAnonymous don't work either.
I've tried changing to and my security tag to xmlns:sec="http://www.thymeleaf.org/extras/spring-security" from xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
SECURITY CONFIG
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Autowired
private DataSource dataSource;
#Autowired
private CustomAccessDenied accessDeniedHandler;
#Value("${spring.queries.users-query}")
private String usersQuery;
#Value("${spring.queries.roles-query}")
private String rolesQuery;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery).dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/" , "/home").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN, OWNER")
.antMatchers("/register/**").hasAnyRole("ADMIN, CASHIER")
.antMatchers("/staff/**").authenticated()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.permitAll()
.and()
.headers()
.frameOptions().disable()
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler);
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/pics/**", "/fonts/**");
}
}
HTML PAGE
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<title>Home</title>
<div th:replace="fragments/css"></div>
</head>
<body>
<div th:replace="fragments/header"></div>
<main>
<div class="scale-transition scale-out" sec:authorize="isAnonymous()">
<!-- USER NOT LOGGED IN MENU -->
<div class="row" style="margin-top: 25px">
<div class="col s12 m8 offset-m2">
<form id="idcards">
<h1 class="center-align">SWIPE YOUR CARD TO LOGIN</h1>
<h4 class="center-align">TAP GREY BOX IF NOT WORKING</h4>
<input class="center-align grey lighten-3" style="height: 100px; font-size: 60px" id="cardData" type='password' value='' autofocus>
<input class="hide" type="button" value="Fill fields" id="filler2" onClick="fillValuesInTextBoxes()">
</form>
</div>
<div class="row">
<div class="col s12 m8 offset-m2" style="margin-top: 50px">
<h3 class="center-align" style="text-decoration: underline;">ANNOUNCEMENTS</h3>
<div>
<div class="card-panel col s12 m4" th:each="announcementsList: ${announcementsList}">
<p class="col s12 m10 offset-m1" th:text="${announcementsList.text}"></p>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<div th:replace="fragments/footer"></div>
</body>
</html>
DEPENDENCIES
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.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.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.4.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.0.1-jre</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-proc:none</compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<!-- source output directory -->
<outputDirectory>target/metamodel</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>target/metamodel</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
This issue always tend to be resolve by adding missing dependencies or changing the ones you are using. So, first, try changing your POM's dependencies to springsecurity5. If that doesn't work, try adding the following #Bean.
Configuration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect;
#Configuration
public class LeafConfig {
#Bean
public SpringSecurityDialect springSecurityDialect(){
return new SpringSecurityDialect();
}
}
POM
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
Since you are using <artifactId>spring-boot-starter-parent</artifactId>, don't add any version to your Thymeleaf Extras, let Spring Boot manage that for you.
Replaced this
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
with
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
I'm trying to use Spring Boot, Spring Security 4, Thymeleaf.And if the user has role"admin" or anything else.The html block should be shown up.But now it always display on the page.
Here is my html
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<div sec:authorize="hasRole('ROLE_GUEST')">
<p class="bg-info">guest</p>
</div>
<div sec:authorize="hasRole('ROLE_ADMIN')">
<p class="bg-info">you can see this if you have permission to acess role_admin</p>
</div>
And here is my pom.xml i do add the thymeleaf-extras-springsecurity4. Also tried thymeleaf-extras-springsecurity3
<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>
<parent>
<groupId>com.zhongdihang.resp</groupId>
<artifactId>resp-parent</artifactId>
<version>1.0.0</version>
<relativePath>../resp-parent</relativePath>
</parent>
<artifactId>resp-serve</artifactId>
<packaging>war</packaging>
<name>Real estate sharing platform serve</name>
<description>Real estate sharing platform serve</description>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>com.zhongdihang.resp</groupId>
<artifactId>resp</artifactId>
</dependency>
<dependency>
<groupId>com.zhongdihang.resp</groupId>
<artifactId>resp-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
</dependency>
<!-- Optional -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Runtime -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<scope>runtime</scope>
<version>11.2.0.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--mapper -->
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.4.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
And here is my securityconfig
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private RoleService roleService;
#Autowired
private SecurityUserDetailsService userDetailsService;
#Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder);
return provider;
}
#Value("${" + ApplicationConstants.THIS_APP_CONFIG_PREFIX + ".security.debug:false}")
private boolean debug = false;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(daoAuthenticationProvider());
}
private void configureExceptionHandling(ExceptionHandlingConfigurer<HttpSecurity> handler) {
handler.authenticationEntryPoint(new SecurityAuthenticationEntryPoint());
}
private void configureAuthorizeRequests(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry) {
//registry.accessDecisionManager(new SecurityAccessDecisionManager());
registry.antMatchers("/login/**","/auth/**","/api/open/person/**","/api/booking/**","/api/module/menu","/api/booking").permitAll();
List<RoleEntity> list = roleService.findAll();
for (RoleEntity roleEntity : list) {
if(roleEntity.getModule()!=null) {
registry.antMatchers(roleEntity.getModule().getPath()+"/**").hasAuthority(roleEntity.getNumber()).anyRequest().authenticated();
}
}
registry.anyRequest().authenticated();
//registry.anyRequest().hasAnyRole("ADMINISTRATOR");
}
private void configureFilter(HttpSecurity http) throws Exception {
//http.addFilterBefore(new SecurityAuthorizationFilter(sessionrepo),
//UsernamePasswordAuthenticationFilter.class);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable();
configureFilter(http);
configureExceptionHandling(http.exceptionHandling());
configureAuthorizeRequests(http.authorizeRequests());
http.csrf().disable();
http.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.failureHandler(new SecurityAauthenticationFailureHandler())
.successHandler(new SecurityAuthenticationSuccessHandler())
.permitAll();
http.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new SecurityLogoutSuccessHandler())
.permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.debug(debug);
web.ignoring().antMatchers(HttpMethod.OPTIONS);
web.ignoring().antMatchers("/assets/**");
web.ignoring().antMatchers("/**.ico");
web.ignoring().antMatchers("/v2/api-docs");
}
}
Anybody can help me?
thank you so much~
I'm using springboot 1.5.8.RELEASE thymeleaf 3.0.9.RELEASE,so i need to use latest org.thymeleaf.extras.so try to add
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
in you pom.
WHat you are missing here is a tag in your HTML
xmlns:sec="http://www.thymeleaf.org/extras/spring-security".
You don't really need xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4" tag anyways if you're using Springboot.