SpringSecurity gives error 401 Bad Credentials - spring

I am new to Spring Security and was creating a simple app to check authentication and authorization. I am using in memory database. Even when I am giving correct login credentials, I am getting error 401 "Bad Credentials" error.
Also I used permitAll() function at some rest endpoints, yet I get a login prompt on those endpoints also. I tried clearing browser history and cache also yet no success. Please help. I am attaching code.
SecurityConfig.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
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 {
#Autowired
//Authentication using In Memory Database
public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder)throws Exception{
authenticationManagerBuilder.inMemoryAuthentication()
.withUser("user").password("{noop}pass123").authorities("ROLE_USER")
.and()
.withUser("admin").password("{noop}pass123").authorities("ROLE_USER","ROLE_ADMIN");
}
//Authorization
#Override //Overriding configure to use HttpSecurity for web based HTTP requests
public void configure(HttpSecurity httpSecurity)throws Exception{
httpSecurity.
authorizeRequests()
.antMatchers("/protectedbyuserrole*").hasRole("USER")
.antMatchers("/protectedbyadminrole*").hasRole("ADMIN")
.antMatchers("/","/notprotected").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
SpringSecurityApplication.Java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
#SpringBootApplication
#ComponentScan({"com.example.demo","controller"})
#Import({SecurityConfig.class})
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
}
TestSecurityController.Java
package com.example.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TestSecurityController {
#RequestMapping("/")
public String Hello() {
return "Hello World!! ";
}
#RequestMapping("/notprotected")
public String HelloAgain() {
return "Hello from a non protected user!! ";
}
#RequestMapping("/protectedbyuserrole")
public String HelloUser() {
return "Hello User Role!! ";
}
#RequestMapping("/protectedbyadminrole")
public String HelloAdmin() {
return "Hello Admin Role!! ";
}
}
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>1.5.19.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SpringSecurity-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringSecurity-1</name>
<description>SpringSecurity for Authentication and Authorization</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-actuator</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
QUERIES
Also let me know how to use simple passwords which I can use in postman. Should I use {noop} or just simply writing the password like .password("pass123").
Should I use single * or ** asterisk in .antmatchers()
I tried it using Postman also and Firefox also. Same error everywhere.
POSTMAN SCREENSHOT

Specifying a particular method (GET, POST etc.) in RequestMapping is a good practice you may need to follow.
I have shared a basic example which I have done in the past.
You can try in the browser with username as myusername and password as a mypassword
If you still face the problem let me know with your postman screenshot
#Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.withUser("myusername")
.password("mypassword")
.roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.csrf().disable()
.authorizeRequests().antMatchers("/login","/home","/failure").permitAll()
.antMatchers(HttpMethod.POST,"/admin/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT,"/admin/**").hasRole("ADMIN")
.antMatchers(HttpMethod.GET,"/admin/**").hasRole("ADMIN")
.antMatchers(HttpMethod.GET,"/user/**").hasAnyRole("ADMIN","USER")
.antMatchers(HttpMethod.POST,"/user/**").hasAnyRole("ADMIN","USER")
.anyRequest().authenticated();
}
EDIT
The mapping matches URLs using the following rules:
? matches one character
matches zero or more characters
** matches zero or more directories in a path
{spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring"
Refer Path Matcher Here
#RequestMapping(value="/protectedbyuser",method=RequestMethod.GET)
public String Hello() {
return "Hello Protected By User!! ";
}

Related

Okta-Spring Boot keeps throwing 400 response using company provided okta registration information

Our company provided me with new okta registration information. Specifically, the following :
okta.oauth2.issuer=https://purpleid-test.oktapreview.com/oauth2/aaabbbbccc
okta.oauth2.audience=ABC12345
okta.oauth2.client-id=0oaSomeClientId
In my spring boot application, I have the following :
pom.xml
<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 https://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.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
....
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>com.okta.spring</groupId>
<artifactId>okta-spring-boot-starter</artifactId>
<version>2.1.6</version>
</dependency>
</dependencies>
....
</project>
Main class
....
import java.security.Principal;
#SpringBootApplication
public class MessageConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(MessageConsumerApplication.class, args);
}
#RestController
#CrossOrigin
static class RootEndpointRestController {
#GetMapping("/test")
String test(Principal principal){
return "test";
}
}
}
application.properties
management.endpoints.web.exposure.include=env,health,info,beans,refresh,bus-refresh
management.endpoint.health.show-details=ALWAYS
management.endpoint.refresh.enabled=true
server.port=8080
okta.oauth2.issuer=https://ourcompanyid-test.oktapreview.com/oauth2/aaabbbbccc
okta.oauth2.audience=ABC12345
okta.oauth2.client-id=0oaSomeClientId
SecurityConfiguration class
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.web.SecurityFilterChain;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
System.setProperty("https.proxyHost", "internet.proxy.ourcompany.com");
System.setProperty("https.proxyPort", "5555");
http.cors().and()
.authorizeRequests(authorizeRequests -> authorizeRequests.anyRequest().authenticated())
.oauth2ResourceServer().jwt();
}
}
Problem :
Whenever I try to access url like localhost:8080/test or localhost:8080/actuator in the browser (Chrome/Edge), it always returns 400 Bad Request
In the browser URL, this is what shows up
https://ourcompanyid-test.oktapreview.com/oauth2/aaabbbbccc
v1/authorize?
response_type=code&
client_id=0oaSomeClientId&
scope=profile%20email%20openid&
state=I2VByus9KqEt_Zt0ivvG9j_IKtLBldoQrZg-a1SRsYM%3D&
redirect_uri=http://localhost:8080/login/oauth2/code/okta&
code_challenge_method=S256&
nonce=AISpoMaYWFKjp2ZdF_xncSd8LFw7FKTMK9D6G1xbP3o&
code_challenge=hi1EmraZOfOYsdn5rolIaRZO4-pbA8yHtMpIVxjcDP0
However, when I use my personal Okta Developer account registration, it succeeds and redirects me to okta login page when I try to access localhost:8080/test or localhost:8080/actuator in the browser (Chrome/Edge)
My personal Okta Developer account registration looks something like this :
okta.oauth2.issuer=https://dev-123456.okta.com/oauth2/default
okta.oauth2.client-id=0oaMyClientId
okta.oauth2.client-secret=MyClientSecret
I don't have any idea why it would work using my personal Okta registration info and why it would NOT work when I use the Okta registration provided by our company.
Basically, when I use my personal Okta, it redirects to Okta login page just fine. But when I use office provided Okta registration, it returns 400 Bad Request
Is this something to do with my SecurityConfiguration class? Is my configuration class good?
Or, is this something that can be fixed by changing Okta configuration in Okta website?
NOTE: I was informed by the person who created the company okta registration that they created a Single-Page type of Okta registration.
I'd appreciate any comment, explanation or suggestion to fix this.
Thank you.
#RestControllers are OAuth2 resource-servers. Configure it as so. This can be as simple as:
<dependency>
<groupId>com.c4-soft.springaddons</groupId>
<artifactId>spring-addons-webmvc-jwt-resource-server</artifactId>
<version>6.0.4</version
</dependency>
#EnableMethodSecurity
public static class WebSecurityConfig { }
com.c4-soft.springaddons.security.issuers[0].location=https://ourcompanyid-test.oktapreview.com/oauth2/aaabbbbccc
com.c4-soft.springaddons.security.issuers[0].authorities.claims=groups
com.c4-soft.springaddons.security.cors[0].path=/test
Follow link above for samples with more options (servlet VS reactive apps or JWT decoder VS access-token introspection, and last Spring default Authentictaion implementation VS custom ones), and also tips for testing (unit & integration) with mocked OAuth2 identities. Tutorials are providing with instructions for configuring resource-servers with just spring-boot-starter-oauth2-resource-server or spring-addons boot starters building on top of it (and much simplified Java configuration).

Application execution failed and not getting expected outcome

I am developing a simple spring boot application. I am creating a LoginController class and trying to access the API which is present in the LoginController class. I am able to execute the program, but not getting the expected output while I am trying to access the API.
Login Controller
package com.in28minutes.springboot.web.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class LoginController {
#GetMapping("/login")
public String loginMessage() {
return "Welcome to Springboot Application";
}
}
Bootstraping Application
package com.in28minutes.springboot.web.springbootwebexample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootWebExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootWebExampleApplication.class, args);
}
}
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 https://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.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.in28minutes.springboot.web</groupId>
<artifactId>spring-boot-web-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-web-example</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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 run the project several times but don't get the output as expected. Can anyone help me out?
#SpringBootApplication annotation scans the current package and the sub-packages to look for #Component. In your case, LoginController is not in the package, not a sub-package of SpringBootWebExampleApplication.
Either move com.in28minutes.springboot.web.controller in com.in28minutes.springboot.web.springbootwebexample.controller
Or, use #SpringBootApplication(scanBasePackages = "your.package") on your SpringBootWebExampleApplication
package com.in28minutes.springboot.web.springbootwebexample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(scanBasePackages = "com.in28minutes.springboot")
public class SpringBootWebExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootWebExampleApplication.class, args);
}
}
package com.in28minutes.springboot.web.springbootwebexample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#ComponentScan("com.in28minutes.springboot")
public class SpringBootWebExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootWebExampleApplication.class, args);
}
}

SpringMVC Controller is not getting called in spring boot application

I have create one simple spring mvc application using spring boot. But when I am trying to call localhost:8080 its not calling controller of this application. I need to know, where I am doing any mistake. I have mentioned my code below:
Controller class:
package com.gopal.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.gopal.models.Address;
import com.gopal.models.Employee;
#Controller
public class EmployeeMvcController {
public EmployeeMvcController() {
// TODO Auto-generated constructor stub
}
#RequestMapping(value="/", method = RequestMethod.GET)
public String getEmployeeList(ModelMap modelMap) {
System.out.println("starting controller");
List<Employee> employees = new ArrayList<>();
Employee e = new Employee();
e.setFirstName("Gopal");
e.setId(1);
e.setAddress(new Address(1, "BRM College", "Nayatola, Raiser"));
employees.add(e);
modelMap.put("employee", e);
System.out.println("ending controller");
return "welcome.jsp";
}
}
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.gopal</groupId>
<artifactId>restdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>restdemo</name>
<description>Rest Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Main class:
package com.gopal.restdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class RestdemoApplication {
public static void main(String[] args) {
SpringApplication.run(RestdemoApplication.class, args);
}
}
in application.properties, I have nothing. When I am trying to call above mentioned url, nothing is happening. I want my controller should get called. Once controller will get called, I will configure my other stuffs. Please let me know where I am doing any mistakes. Thanks in advance.
Gopal Lal
can you please try with #ComponentScan like below:
package com.gopal.restdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#ComponentScan(basePackages={"com.gopal.controllers"})
public class RestdemoApplication {
public static void main(String[] args) {
SpringApplication.run(RestdemoApplication.class, args);
}
}
and try with localhost:8080/ with GET request
The problem is that your bean controller is not scanned:
package com.gopal.controllers; -> controller package
com.gopal.restdemo; -> spring boot application package
If you don't add #ComponentScan("com.gopal") on your SpringBootApplication, by default it will scan the package where it is located : "com.gopal.restdemo".
If you will move your SpringBootApplication in common package for both of them, your problem will be fixed:
Move RestdemoApplication to com.gopal

There was an unexpected error (type=Not Found, status=404). No message available

I am getting below error:
There was an unexpected error (type=Not Found, status=404). No message available
While using Spring Boot + Thymeleaf
Code:
Application class:
package com.mycom.extract;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
#SpringBootApplication(scanBasePackages = "com.mycom.extract")
public class MyAppExtractionWebApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(MyAppExtractionWebApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyAppExtractionWebApplication.class);
}
}
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.mycom.extract</groupId>
<artifactId>MyApp-extraction</artifactId>
<version>1</version>
<packaging>war</packaging>
<name>MyAppExtractionWeb</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.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-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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</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>
SecurityConfig
package com.mycom.extract.config.security;
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private MyAppAuthenticationProvider authProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**", "/login").permitAll()
.antMatchers("/*").fullyAuthenticated()
.and()
.formLogin().loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("ipn").passwordParameter("password")
.defaultSuccessUrl("/home").failureUrl("/login?error")
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
http.csrf().disable();
}
}
WebMvcConfiguration
package com.mycom.extract.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#EnableAutoConfiguration
#Configuration
#ComponentScan(basePackages = { "com.mycom.extract" })
public class MyAppConfiguration extends WebMvcConfigurerAdapter{
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "/login");
registry.addViewController("/login").setViewName("index");
registry.addViewController("/home").setViewName("home");
}
}
Referring all same kind of post in Stackoverflow could find solution for myself.
Please suggest.
URL http://localhost:8080/MyAppExtractionWeb/
As I am setting up login, and authentication is handled at security config side, so once it is successful it shows home page. Hence no controller mentioned.
package com.mycom.config.security;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import org.springframework.beans.factory.annotation.Autowired;*/
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import com.mycom.entity.User;
import com.mycom.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Configuration
public class MyAppAuthenticationProvider implements AuthenticationProvider {
private static final String SECURITY_DOMAIN = "MyApp-ldapdomain";
#Autowired
private UserService userService;
#Override
public Authentication authenticate(Authentication authentication) {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
try {
CallbackHandler handler = new UserPasswordHandler(name, password);
LoginContext lc = new LoginContext(SECURITY_DOMAIN, handler);
lc.login();
if(lc.getSubject() != null) {
User user = userService.loadUserByUsername(name);
Collection<? extends GrantedAuthority> roles = null;
if(!user.getAuthorities().isEmpty()) {
roles = user.getAuthorities();
}
return new UsernamePasswordAuthenticationToken(name, password,roles);
} catch (Exception e) {
return null;
}
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}

Spring Boot mapping action to view(.html) not working

I have a spring boot basic application
package com.meenakshi.fileupload;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Example {
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
My controller is
package com.meenakshi.fileupload.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class IndexController {
#RequestMapping("/")
public String index() {
System.out.print("REDIRECTED BY MEENAKSHI");
return "index";
}
}
My index.html is a basic html file in src/main/resources/public folder
My pom.xml is
<?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.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</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>
<!-- Additional lines to be added here... -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
When I do localhost:8080 I expect to redirect to index.html but I am getting Whitelabel Error Page
When I add thymeleaf dependency and add xmlns:th="http://www.thymeleaf.org" in .html it works
How to resolve it? Also what is the default view resolver in Spring Boot? Do I compulsorily need to use thymeleaf?
Also, do I need to add something to application.properties
There are couple of ways you can expose your index.html.
The way I like the most is doing the following:
#Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index.html");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
It will automatically grab your index.html and create a default view controller to serve it.
Another way is doing like you did but returning ModelAndView like the following but it suit a Thymeleaf/JSP more then a SPA:
#Controller
#RequestMapping("/")
public class DefaultController {
#GetMapping("/")
public ModelAndView index() {
IndexModel indexModel = new IndexModel();
return new ModelAndView("index", "index", indexModel);
}
}

Resources