Spring : Always say forbidden - Status 403 - java

I have configured all the settings for my spring project, but when I try to login in to the application, it says for each request that
"The server understood the request but refuses to authorize it."
Initially I tried to implement JDBC Authentication, (you can see that I am using the Datasource in my code). But then I tried with in memory authentication too, in both cases, I am unable to access the resources.
Below is my spring config file,
package com.nobalg.config;
import java.beans.PropertyVetoException;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.mchange.v2.c3p0.ComboPooledDataSource;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages="com.nobalg")
#PropertySource("classpath:persistence-mysql.properties")
public class AppConfig {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public DataSource secureDataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
//Datasource
dataSource.setDriverClass(env.getProperty("jdbc.driver"));
dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
dataSource.setUser(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.password"));
//Connection polling
dataSource.setInitialPoolSize(Integer.parseInt(env.getProperty("connection.pool.initialPoolSize")));
dataSource.setMaxPoolSize(Integer.parseInt(env.getProperty("connection.pool.maxPoolSize")));
dataSource.setMinPoolSize(Integer.parseInt(env.getProperty("connection.pool.minPoolSize")));
dataSource.setMaxIdleTime(Integer.parseInt(env.getProperty("connection.pool.maxIdleTime")));
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
return dataSource;
}
}
Dispatcher Servlet Initializer file
package com.nobalg.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MvcSpringInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class[]{AppConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}
}
Spring security configuration file :
package com.nobalg.config;
import javax.sql.DataSource;
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 SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//auth.jdbcAuthentication().dataSource(dataSource);
auth.inMemoryAuthentication().withUser("Nobal").password("test#123").authorities("MANAGER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/loginPage")
.loginProcessingUrl("/loginProcessing")
.usernameParameter("username")
.passwordParameter("password")
.permitAll();
}
}
Spring security initializer file
package com.nobalg.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
The one and only controller
package com.nobalg.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class MainContoller {
#GetMapping("/loginPage")
public String showLoginForm(){
return "login";
}
}
and the login page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form method="POST" action="${pageContext.request.contextPath}/loginProcessing">
<p>Enter Username : <input type="text" placeholder="Enter Username" name="username"></p>
<p>Enter Password : <input type="password" placeholder="Enter Password" name="password"></p>
<p><input type="submit" value="LOG IN"></p>
</form:form>
</body>
</html>

Add this as your form field:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
Or if you want other approach with Spring Security JSP tag library:
Optionally you can disable csrf, which is enabled by default:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
Edit1
Add this bean with passwordEncoder.
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
And set password encoder to auth:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.passwordEncoder(this.passwordEncoder());
}
Edit2
Change .loginProcessingUrl("/loginProcessing") which needs UserDetailsService to .defaultSuccessUrl("/")

Related

Spring security login form does not work when there is servlet Url: localhost: 8080 / nameWeb / login

I'm building a spring mvc application and include spring security for logging in and out, but when I add the context of the root 'TechZone' behind: "localhost: 8080 / TechZone / login" it doesn't work , it seems that the default security application only accepts "localhost: 8080 / login". How to correctly configure the servlet url customization, if anyone knows please help me and I appreciate it!
package com.techzone.springmvc.config;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
#EnableTransactionManagement
public class DatabaseConfig extends WebMvcConfigurerAdapter {
final static String PACKAGE_SCAN = "com.techzone.springmvc";
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", true);
properties.put("hibernate.format_sql", true);
properties.put("hibernate.hbm2ddl.auto", "update");
return properties;
}
#Bean(name = "dataSource")
public BasicDataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/TechZone?useSSL=false");
dataSource.setUsername("springstudent");
dataSource.setPassword("springstudent");
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactoryBean(BasicDataSource dataSource) {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setPackagesToScan(PACKAGE_SCAN);
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
// #Bean /** PersistenceJPAConfig **/
// public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
// LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
// factory.setDataSource(getDataSource());
// factory.setPackagesToScan(PACKAGE_SCAN);
// JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
// factory.setJpaVendorAdapter(vendorAdapter);
// factory.setJpaProperties(hibernateProperties());
//
// return factory;
// }
// #Bean
// public HibernateTransactionManager transactionManager(SessionFactory session) {
// HibernateTransactionManager manager = new HibernateTransactionManager();
// manager.setSessionFactory(session);
// return manager;
// }
//
// #Bean
// public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
// return new PersistenceExceptionTranslationPostProcessor();
// }
}
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
// AUTO
}
package com.techzone.springmvc.config;
import javax.annotation.Resource;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "userDetailService")
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("**/login"))
.and().authorizeRequests()
.antMatchers("**/login").permitAll()
.antMatchers("/dashboard").hasRole("USER")
.and().formLogin().defaultSuccessUrl("/dashboard").loginProcessingUrl("/login")
.loginPage("/login").and().logout().permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/*.css");
web.ignoring().antMatchers("/*.js");
}
#Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
package com.techzone.springmvc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#ComponentScan({"com.techzone.springmvc"})
public class MvcConfig extends WebMvcConfigurerAdapter { // TODO INFO: This's the dispatcher servlet's Spring application context //
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/*.js/**").addResourceLocations("/views/static/");
registry.addResourceHandler("/*.css/**").addResourceLocations("/views/static/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resourceView = new InternalResourceViewResolver();
resourceView.setViewClass(JstlView.class);
resourceView.setPrefix("/views/jsp/");
resourceView.setSuffix(".jsp");
return resourceView;
}
// for upload image
#Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
// multiple Language
#Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
interceptorRegistry.addInterceptor(localeChangeInterceptor).addPathPatterns("/*");
}
}
package com.techzone.springmvc.config;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
// TODO : Create the root spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(MvcConfig.class, DatabaseConfig.class,MessageResourcesConfig.class,SpringSecurityConfig.class);
// TODO : Manager life cycle of the root application context
servletContext.addListener(new ContextLoaderListener(rootContext));
// TODO : Create the dispatcher servlet's spring application context
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(MvcConfig.class);
// TODO : Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
// TODO : Filter Character UTF-8
FilterRegistration.Dynamic filter = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
filter.setInitParameter("encoding", "UTF-8");
filter.setInitParameter("forceEncoding", "true");
filter.addMappingForUrlPatterns(null, true, "/*");
}
}
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
isELIgnored="false" pageEncoding="UTF-8"%>
<html>
<head>
<title>Spring Security Example</title>
<link href="/bootstrap.min.css" rel="stylesheet">
<script src="/jquery-2.2.1.min.js"></script>
<script src="/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin: 50px;border: 1px solid green;">
<h3>Spring Security Login Example</h3>
<c:if test="${param.error ne null}">
<div style="color: red">Invalid credentials.</div>
</c:if>
<form action="/login" method="post">
<div class="form-group">
<label for="username">UserName:</label> <input type="text"
class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label> <input type="password"
class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-success">Submit</button>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
</div>
</body>
</html>
**
I expect it work with localhost:8080/nameYourApp/login instead of localhost:8080/login
**
Pic1
Pic2
You can define, complete path for security login (new AntPathRequestMatcher("/TechZone/login"));

Spring security cannot loggin with current password

I'm making with using spring and hibernate. In my database i'm having several users with 3 different roles. I'm using BCryptPasswordEncoder, in database i'm having users with plain password, encoded password and {bcrypt}encoded password, i'm having problem becouse when i type users with plain passwords i can login, when i type password encoded or {bcrypt}encoded i can't login.
SecurityConfig.java
package com.spring.config;
import com.spring.service.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth ) throws Exception {
auth.authenticationProvider(authProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/managers/**").hasRole("MANAGER")
.antMatchers("/employees/**").hasRole("REGULAR_EMPLOYEE")
.antMatchers("/").permitAll()
.and().formLogin().loginPage("/").defaultSuccessUrl("/login").loginProcessingUrl("/loginAction").permitAll()
.and().logout().permitAll();
}
#Bean
public UserDetailsService userDetailsService(){
return new UserDetails();
}
#Autowired
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(bCryptPasswordEncoder());
return authProvider;
}
}
UserDetails.java
package com.spring.service;
import com.spring.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class UserDetails implements UserDetailsService {
#Autowired
private UserService mUserService;
#Override
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = mUserService.getUserByLogin(s);
org.springframework.security.core.userdetails.User.UserBuilder userBuilder;
userBuilder = org.springframework.security.core.userdetails.User.withUsername(user.getAccountLogin());
userBuilder.password(new BCryptPasswordEncoder().encode(user.getAccountPassword()));
userBuilder.roles(user.getRoleByRoleId().getRole());
return userBuilder.build();
}
}
plain-login.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Log in</title>
<meta charset="UTF-8">
<style>
.failed {
color: red;
}
.success {
color: green;
}
</style>
</head>
<body>
<form:form action="${pageContext.request.contextPath}/loginAction"
method="POST">
<c:if test="${param.error != null}">
<i class="failed">Wrong data!</i>
</c:if>
<c:if test="${param.logout != null}">
<i class="success">Logged out successfully!</i>
</c:if>
<p>
Login: <input type="text" name="username" />
</p>
<p>
Password: <input type="password" name="password" />
</p>
<input type="submit" value="Log in" />
</form:form>
</body>
</html>

Spring MVC application with 404 error

My Spring release is 5.x and tomcat version is 8.5, so according to introduction, they will support the web application running without web.xml, but I got 404 error, see my project structure below:
I use this url to access my application, but got 404 error:
http://localhost:8080/SpringMVC/
see my code below:
RootConfig.java:
package spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages= {"spitter"},
excludeFilters= {#Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)}
)
public class RootConfig {
}
WebConfig.java:
package spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("spittr.web")
public class WebConfig implements WebMvcConfigurer{
public ViewResolver viewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}
SpittrWebAppInitializer.java:
package spittr.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
HomeController.java:
package spittr.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#RequestMapping(value="/",method=RequestMethod.GET)
public String home()
{
System.out.println("test");
return "home";
}
}
home.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>this is the Home Jsp page</title>
</head>
<body>
<h1>Hello, Spring MVC!</h1>
</body>
</html>
from the Eclipse console, I can see output "test" that means spring context find out the controller, but seems it cannot find the jsp page, I don't know the reason, can someone tell me what's wrong with my code?
Try adding #Bean annotation on top of WebConfig#viewResolver() method. So, the Spring Container manage your method as bean and your custom configuration will probably work.
#Bean
public ViewResolver viewResolver(){}
Indicates that a method produces a bean to be managed by the Spring
container.

Spring Security - Simple User Registration (not xml configuration)

I have only 2 page in my project "/register" and "/login". login.jsp page is coming from default spring security login. register.jsp is created by me.
My spring security configuration:
package com.cihangirmercan.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;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("cihangir").password("mercan")
.roles("USER"); // the only user at the beginning
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login", "/register").permitAll() // anonym can login or register
.antMatchers("/").access("hasRole('USER')") // home page is not allowed if not user is logged in
.and().formLogin();
http.csrf().disable();
}
}
So, in the beginning, only one user id:"cihangir" and pass:"mercan" can pass the filter and login. What I want is after register with username and password, I want this new registration to has ROLE_USER and can login after that.
RegisterController:
package com.cihangirmercan.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;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
#Controller
#SessionAttributes("registerWarning")
public class RegisterController {
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String showRegisterPage(ModelMap model) {
return "register";
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String handleRegisterRequest(ModelMap model,
#RequestParam String username,
#RequestParam String password) {
// i want to give this username and password ROLE_USER
// hence user can login with spring security
// done
return "redirect:/login";
}
}
register.jsp:
<html>
<head>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<form action="/register" method="post" >
<label>Username:</label>
<input type="text" name="username" required><br><br>
<label>Password:</label>
<input type="password" name="password"><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
WelcomeController: (welcome page)
package com.cihangirmercan.controller;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
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 WelcomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String showWelcomePage(ModelMap model) {
model.put("username", getLoggedInUserName());
return "welcome";
}
private String getLoggedInUserName() {
Object principal = SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
if (principal instanceof UserDetails)
return ((UserDetails) principal).getUsername();
return principal.toString();
}
}
welcome.jsp:
<html>
<head>
<title>Home</title>
</head>
<body>
<h2>Home Page</h2>
<br>
<h4>${username} is at home.</h4>
</body>
</html>
Besides, web.xml and dispatcher-servlet and pom.xml they are all I have.
you have not configured your login correctly
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login", "/register").permitAll() // anonym can login or register
.antMatchers("/").access("hasRole('USER')") // home page is not allowed if not user is logged in
.and().formLogin().loginPage("/login")
.and()
.logout().logoutSuccessUrl("/register");
http.csrf().disable();
}
and you have configured the view resolver in your dispatch-xxx.xml, something like this
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
I solved my problem with using jdbc authentication.
It dynamically updates users and roles.
source: https://dzone.com/articles/spring-security-4-authenticate-and-authorize-users

WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI

I am getting this error while adding Assets folder.
It is giving error for every file which is included from "assets" folder.
WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/assets/plugins/datepicker/datepicker3.css] in DispatcherServlet with name 'dispatcher'
Here is the Dispacther Config file
package com.springmaven.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan({"com.springmaven.controller"})
public class DispatcherConfig {
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver()
{
InternalResourceViewResolver internalResourceViewResolver=new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/JSP/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
This is App Config
package com.springmaven.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class AppIntializer implements WebApplicationInitializer{
#Autowired
public void onStartup(ServletContext servletCon) throws ServletException {
// TODO Auto-generated method stub
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ApplicationConfig.class);
servletCon.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext servletConfig = new AnnotationConfigWebApplicationContext();
servletConfig.register(DispatcherConfig.class);
ServletRegistration.Dynamic registration = servletCon.addServlet("dispatcher", new DispatcherServlet(servletConfig));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
This is security Config
package com.springmaven.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
private AuthenticationProvider customAuthenticationProvider;
#Autowired
CustomSuccessHandler customSuccessHandler;
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/assets/**");
}
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationProvider(customAuthenticationProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/assets/**").permitAll()
.and()
.formLogin().loginPage("/loginPage")
.defaultSuccessUrl("/homePage")
.failureUrl("/loginPage?error")
.usernameParameter("username").passwordParameter("password")
.and().csrf().csrfTokenRepository(csrfTokenRepository())
.and()
.logout().logoutSuccessUrl("/loginPage?logout");
}
#Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
private CsrfTokenRepository csrfTokenRepository()
{
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setSessionAttributeName("_csrf");
return repository;
}
}
Folder Structure
source->main->webapp->WEB-INF->JSP->assets(This folder is not recognised)
source->main->webapp->WEB-INF->JSP->homePage.jsp
From the Style or Icon is not coming in homePage.
homePage.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>New Member</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<!--Favicon Image -->
<link rel="shortcut icon" href="assets/dist/img/favicon.ico"/>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="assets/plugins/datepicker/datepicker3.css">
</head>
<body>
Welcome,
<form id="logout" action="${Signout}" method="post" >
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:if test="${pageContext.request.userPrincipal.name != null}">
Logout
</c:if>
</body>
</html>
You need to add support for static web resources.
To configure it to be managed by Spring see this question, for example.

Categories

Resources