I'm developing a simple Java web application with SpringMVC. With security enabled, I cannot send a HTTP post request (from the index.jsp) to the server although I am already authenticated. POST request does work when the security isn't implemented. So I think it's a problem with my SecurityConfig.java code.Could you please help me with this? Thanks very much
Error Code :
HTTP Status 403 – Forbidden
Type Status Report
Message Forbidden
Description The server understood the request but refuses to authorize it.
This is my security configuration.
SecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("{noop}123456").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.authorizeRequests()
.antMatchers("/index").hasRole("USER")
.antMatchers(HttpMethod.POST, "/index").hasRole("USER");
}
}
index.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<!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=UTF-8">
<title>Registration</title>
</head>
<body>
<form action='#{/index}' method="POST">
<div class="form-group">
<td><textarea class="form-control" name="textForm">${text1}</textarea>
<input type="submit" value="Submit">
<textarea name="textFin">${textFinal}</textarea></td>
</form>
</div>
</body>
</html>
Add
http.csrf().disable(); to configure method.
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.authorizeRequests()
.antMatchers("/index").hasRole("USER")
.antMatchers(HttpMethod.POST, "/index").hasRole("USER")
.and()
.csrf().disable();
}
You are confusing jsp with thymleaf. Edit the jsp file to:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<!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=UTF-8">
<title>Registration</title>
</head>
<body>
<form:form action="/index" method="POST">
<div class="form-group">
<td><textarea class="form-control" name="textForm">${text1}</textarea>
<input type="submit" value="Submit">
<textarea name="textFin">${textFinal}</textarea></td>
</form:form>
</div>
</body>
</html>
The UserDetailService bean that you have provided didn't work for me. I had to change it like this:
#Bean
public UserDetailsService userDetailsService() {
// ensure the passwords are encoded properly
#SuppressWarnings("deprecation")
UserBuilder users = User.withDefaultPasswordEncoder();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(users.username("me").password("me").roles("USER").build());
return manager;
}
When we enable web security, for every form submitted, we need to send the _crsf(cross-site request forgery) token which is generated randomly base on the user's session.
If we don't want to use this token, we can disable it by calling .csrf().disable()
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.and()
.authorizeRequests()
.antMatchers("/index").hasRole("USER")
.antMatchers(HttpMethod.POST, "/index").hasRole("USER")
.and()
.csrf().disable();
}
But, in the real world, the token is preferred for security purposes. There are 2 approaches to generate the token.
Approach 1: Generating token automatically by form tag <form:form>. Spring MVC will help us generated the token behind the scenes.
use taglib:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
and modify <form action='#{/index}' method="POST"> to:
<form:form action='#{/index}' method="POST">
// our html code
</form:form>
Approach 2: Generating token manually by adding the hidden field.
Before the close form tag </form>, add the following code.
<form action='#{/index}' method="POST">
// our html code
...
<input type="hidden" name="_csrf.parameterName" value="_csrf.token" />
</form>
Related
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 3 years ago.
I am making a login .JSP where on login button it called to login.java(servlet). But JSP is not able to call the servlet file and it gives an error.
Login.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login</title>
</head>
<body>
<form action="Login" method="get">
Enter Username:<input type="text" name="uname"><br>
Enter Password:<input type="password" name="upass"><br>
<input type="submit" value="login">
</form>
</body>
</html>
Login.java(servlet file)
package com.login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Login
*/
#WebServlet("/Login")
public class Login extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String uname=request.getParameter("uname");
System.out.print("uname is"+uname);
String upass=request.getParameter("upass");
if (uname.equals("meet") && upass.equals("1234")) {
response.sendRedirect("welcome.jsp");
}
else {
response.sendRedirect("login.jsp");
}
}
}
ERROR MESSAGE
HTTP Status 404 – Not Found
Type Status Report
Message /Login
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Simply you can use getConextPath in jsp request
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/Login" method="get">
Enter Username:<input type="text" name="uname"><br>
Enter Password:<input type="password" name="upass"><br>
<input type="submit" value="login">
</form>
</body>
</html>
Wish i was helpfull; but regarding to BalusC using Scriptlets <% ... %> are officially discouraged since JSP 2.0 which was introduced in 2003(!!). Please do not encourage starters to use bad practices. The correct practice is to use EL ${ ... } instead. –
so you can write this way and always try to use it on this way
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login</title>
</head>
<body>
<form action="${requestScope.getContextPath}/Login" method="get">
Enter Username:<input type="text" name="uname"><br>
Enter Password:<input type="password" name="upass"><br>
<input type="submit" value="login">
</form>
</body>
</html>
Its better to know the bad coding and the write coding , wish i this help you too.
I have a simple java application where I would like all my pages to have access to the style sheet folder and files even if the user has not been authenticated. I have the following code in my WebSecurityConfig.java file:
package com.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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
// Add WebSecurityConfig class to configure security
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String USER = "USER";
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/security").permitAll()
.antMatchers("/css/**.css").permitAll()
.antMatchers("/hands_on").hasAnyRole(USER)
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
I have this code in my hands_on.html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>hands on Demo</title>
<link th:href="#{/css/style.css}" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>hands on Demo</h1>
</body>
</html>
And I have this code in my login.html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Demo</title>
<link th:href="#{/css/style.css}" rel="stylesheet" type="text/css" />
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="#{/login}" method="post">
<div><label> Enter your User Name : <input type="text" name="username"/> </label></div>
<div><label> Enter your Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
If I start my java application and launch a browser and go to localhost:8080/hands_on I would expect the login page to get displayed and be presented with my style sheet. What happens is the login page gets displayed but without the styles being applied. When I look at my javascript console, I see this:
Refused to apply style from 'http://localhost:8080/css/style.css' because its MIME type ('application/json') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
My style.css file is in the folder security[boot]/src/main/resources/static/css.
I thought I would have access to the style.css file based on the .antMatchers("/css/**.css").permitAll() in my WebSecurityConfig.java file but I guess I am missing something. Ideas?
I am trying to create a sample registration page with Spring MVC and JSP pages.
While opening the url on tomcat server, I am getting following error
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'register' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(
I have a JSP register.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration</title>
</head>
<body>
<form:form action="/register/process" method="POST" modelAttribute="register">
<table style="text-align: center;">
<tr>
<td><form:label path="fname">First Name</form:label></td>
<td><form:input path="fname" name="fname"
id="fname" /></td>
</tr>
<tr>
<td><form:label path="lname">Last Name</form:label></td>
<td><form:input path="lname" name="lname" id="lname" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="CREATE AN ACCOUNT"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
I have a controller class UserController.java
package vnfhub.supplier.controller;
#Controller
public class UserController {
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String getRegisterForm(Model model) {
model.addAttribute("register", new Register());
return "register";
}
#RequestMapping(value = "/register/process", method = RequestMethod.POST)
public String processRegistration(#ModelAttribute("register") Register register, BindingResult result) {
return "success";
}
}
and a success.jsp page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Success Form</title>
</head>
<body>
<font color="green"><h1>Hello</h1></font>
<h1>You have successfully registered</h1>
<font color="green"><h1>Welcome to Spring world !</h1></font>
</body>
</html>
I have tried many solution on stackoverflow.... but none of them worked.
I find your code okay so far as you given here. I mimic the situation with your code but unfortuantely found No Exception.
Things that you might have doing wrong is you are running some old build code in your tomcat. try to clean build and re-deploy in your container.
NB: one friendly suggestion. You are doing one thing wrong that is having action of your form to /register/process that will send the request to the container root (e.g. localhost:8080/register/process). And you will get 404 for that. You are not probably want that. register/process should be your URL and this will POST the request relative to your application-context. If your application context is something localhost:8080/test, this will send the request to localhost:8080/test/register/process
I'm new at spring, but here I have some problem, and I cant find any answer.
So, I need to set access for a registration page, only for users who have a link from admin. I see that like, admin send the link and only one user can enter and register, after that link will be unavailable.
First of all, I know that admin should generate some link, but I don't know how to.
And I don't know how to set that access from a link. Well, I can say that I don't know anything :)
Can you help me? Like I cant even find some tutorials or information about this.
The code is:
protected void configure(final HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/index").hasAnyRole(USER, ADMIN)
.antMatchers("/admin").hasRole(ADMIN)
.antMatchers("/addUser").hasRole(ADMIN)
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/index")
.failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling()
.accessDeniedPage("/login")
.and()
.rememberMe()
.rememberMeParameter("remember-me")
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(900);
}
Admin page where is button for register new user
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page isELIgnored="false" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Users List</title>
<link href="<c:url value='/resources/css/bootstrap.min.css' />" rel="stylesheet"></link>
</head>
<body>
<div class="generic-container">
<%--<%#include file="authheader.jsp" %>--%>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading"><span class="lead">User Administration</span></div>
<table class="table table-hover">
<thead>
<tr>
<th>Username</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Role</th>
<sec:authorize access="hasRole('ADMIN')">
<th width="100"></th>
</sec:authorize>
<sec:authorize access="hasRole('ADMIN')">
<th width="100"></th>
</sec:authorize>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.username}</td>
<td>${user.firstname}</td>
<td>${user.lastname}</td>
<td>${user.email}</td>
<td>${user.roles}</td>
<sec:authorize access="hasRole('ROLE_ADMIN')">
<td>edit</td>
</sec:authorize>
<sec:authorize access="hasRole('ROLE_ADMIN')">
<td>delete</td>
</sec:authorize>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<sec:authorize access="hasRole('ADMIN')">
<div class="well">
Add New User
</div>
</sec:authorize>
</div>
</body>
</html>
If you well need some additional code, tell me.
Sorry if something wrong, it's my second question here.
You can generate a token (which will be hard to guess)
UUID id = UUID.randomUUID();
String t = id.toString();
//your link generation goes here
String link = baseUrl+"/register?token="+t;
//Save the token in db with a field expired=false
Token token = new Token();
token.setUuid(t);
token.setCreatedDate(new Date());
token.setExpired(false);
tokenRepo.save(token)
In the request handling, get the token into the RestController and
//let t be the captured token
Token token = tokenRepo.findByUuid(t);
if(token.expired){
//tell them link is expired
}else{
token.setExpired(true)
//give them the reg page and take it from here
}
This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 6 years ago.
I want to perform multiple operation Like DELETE and UPDATE to do so I Need to send Data to Controller,
where I Am doing Mistake??
Following is my JSP 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" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<jsp:useBean id="TimeDetailBean" class="com.logic.bean.userBean" scope="application" />
<!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>Manage Results</title>
</head>
<body>
<center>
<h1>The Employee_Info Results </h1>
<table>
<tr><th>Name</th><th>Last name</th><th>Password</th></tr>
<c:forEach items="${rows}" var="row">
<tr>
<td><input type="text" name="name" value=${row.NAME}></td>
<td><input type="text" name="lastname" value=${row.LASTNAME}></td>
<td><input type="text" name="password" value=${row.PASSWORD}></td>
<td>UPDATE</td>
<td>DELETE</td>
</tr>
</c:forEach>
</table>
</center>
</body>
</html>
and below is the controller where I want The value of name ,lastname and password
#RequestMapping("/delete")
public ModelAndView Delete(HttpServletRequest request, HttpServletResponse response)
{
System.out.println("Delete Controller Executed");
userBean ub= new userBean();
Dao d= new Dao();
String name=request.getParameter("name");
String lastname=request.getParameter("lastname");
System.out.println("Name catch"+name);
System.out.println("Lastname catch"+lastname);
return new ModelAndView("deleteSuccess");
}//delete ends
Thanks in advance. .
In order to send the Data from JSP to Controller
Create a form with action (/delete) and method=POST
Create a Controller with the #RequestMapping("/delete") that point to form action
Use Request.getParameter("name") in Controller.
Now on submit button in the JSP Spring Servlet Dispatcher will the mapping form in the Controller class and send the data to the controller from JSP.
Let us know if more inforamtion needed I will share the sample example
Regards,
Pavan