Spring Security Redirect if no access on page - redirect

I have a j2ee web application using spring web flow ang spring security. I want to redirect the user to page(maybe an error page) if the user's role has no access on the page being accessed because currently I get the error
Error 404--Not Found
From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:
10.4.5 404 Not Found
The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent.
If the server does not wish to make this information available to the client, the status code 403 (Forbidden) can be used instead. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address.
How do I do this redirection.I tried the access-denied-page attribute of security:http but I still get the error. Here's my configuration for security-http.
By the way.I am using Spring Faces and Facelets. Could this have been the cause of the problem?
<!-- Configure Spring Security -->
<security:http auto-config="true" access-denied-page="/deniedpage.xhtml"
session-fixation-protection="newSession">
<security:intercept-url pattern="/main.do"
access="ROLE_SUPERVISOR, ROLE_USER" />
<security:intercept-url pattern="/logoutSuccess.do"
access="ROLE_SUPERVISOR, ROLE_USER" />
<security:intercept-url pattern="/edit.do"
access="ROLE_SUPERVISOR" />
<security:intercept-url pattern="/register.do"
access="ROLE_SUPERVISOR" />
<security:intercept-url pattern="/admin_main.do"
access="ROLE_SUPERVISOR" />
<security:intercept-url pattern="/*"
access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:form-login login-page="/loginForm.do"
default-target-url="/main.do" authentication-failure-url="/loginForm.do?login_error=1" />
<security:logout logout-url="/logout.do"
invalidate-session="true" logout-success-url="/logoutSuccess.do" />
<security:concurrent-session-control
max-sessions="-1" exception-if-maximum-exceeded="true" expired-url="/loginform.do" />
</security:http>

The access-denied-page attribute of security:http should be enough, show us the Spring configuration you are using.
In the meantime try adding this to web.xml:
<error-page>
<error-code>404</error-code>
<location>notfound.jsp</location>
</error-page>

Related

Spring security - GWT redirect after Authentication

I have a GWT application that I am trying to login using spring security. Currently, after a successful login, I am redirected back to the Login page. I am guessing this is because of my spring configuration and my lack of spring security knowledge.
In my spring-security.xml I define my intercepts like so:
<security:http auto-config="true">
<security:intercept-url pattern="/login" access="permitAll" />
<security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>
I am guessing that the issue is on the access=isAuthenticated() but I am not sure. I want it to redirect to the gwt page/app which will handle the view based on the role returned. I made a very simple gwt app with this method and it worked.
I am using the Spring generated login page and not a JSP.
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:b="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!-- This is where we configure Spring-Security -->
<security:http auto-config="true">
<security:intercept-url pattern="/login" access="permitAll" />
<security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>
<b:bean id="graplAuthentication" class="com.foo.rim.security.GraplAuthentication"/>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="graplAuthentication" />
</security:authentication-manager>
</b:beans>
This turned out to be two things.
1) I needed to add the user-expressions="true" so it would pick up the access=
<security:http auto-config="true" use-expressions="true">
2) I had a custom user Authentication class and forgot to set the the Authenticated boolean to true. Both of these got it working correctly.

REST service returns bad gateway when file is big and processing takes too long

I have made a REST service that receives a ZIP-file, process and check some stuff, and returns an ID. This works fine for smaller ZIP-files, but when sending larger files (currently testing with 17 Mb), and the processing takes longer, the service returns "502 Bad gateway - Web server received an invalid response while acting as a gateway or proxy server".
I have tried to change all the variables I could find in the web config:
<binding name="webHttpTransportSecurity" maxReceivedMessageSize="163840000" maxBufferSize="163840000" closeTimeout="04:00:00" openTimeout="04:00:00" receiveTimeout="04:00:00" sendTimeout="04:00:00">
<security mode="Transport">
<transport clientCredentialType="Windows" />
</security>
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
<httpRuntime maxRequestLength="2147483647" enable="true" requestLengthDiskThreshold="10240" useFullyQualifiedRedirectUrl="true" executionTimeout="1000" appRequestQueueLimit="4000000" />
<serviceBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</serviceBehaviors>
Anyone have any idea how to make this work with bigger files? Where is this restriction, in IIS or something?
UPDATE: my code on server continue to run in the background and receives the whole file even though the caller of the service gets 'bad gateway'. So this is a 'false' 502.

WF Workflow Service Error Cannot obtain Metadata from http://localhost/OrderService/Service1.xamlx

I have created a Workflow service using Microsoft WF (https://msdn.microsoft.com/en-us/library/ff432975%28v=vs.110%29.aspx)
When i run the service in visual studio I'm getting the below error
Error: Cannot obtain Metadata from http://localhost/OrderService/Service1.xamlx
If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address.
For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: http://localhost/OrderService/Service1.xamlx
Metadata contains a reference that cannot be resolved: 'http://localhost/OrderService/Service1.xamlx'.
The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.HTTP GET Error URI: http://localhost/OrderService/Service1.xamlx
There was an error downloading 'http://localhost/OrderService/Service1.xamlx'. The request failed with an empty response.
My config is below. I have added the Meta Exchange lines in the config file also.
<system.serviceModel>
<services>
<service behaviorConfiguration="metadataBehavior" name="MyService">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
<!--Connection String for the WF SQL Presistance-->
<sqlWorkflowInstanceStore connectionString="Data Source=AAAAA;Initial Catalog=KK_SQLPersistenceStore;Asynchronous Processing=True" instanceEncodingOption="None" instanceCompletionAction="DeleteAll" instanceLockedExceptionAction="BasicRetry" hostLockRenewalPeriod="00:00:30" runnableInstancesDetectionPeriod="00:00:02" />
<workflowIdle timeToUnload="0"/>
</behavior>
</serviceBehaviors>
</behaviors>
Try changing you endpoint address to this
<endpoint address="http://localhost/OrderService/Service1.xamlx/mex" binding="mexHttpBinding" contract="IMetadataExchange" />

What is the difference between customErrors and httpErrors?

What is the difference between the customErrors and httpErrors sections of the web.config file in ASP.NET MVC applications?
What are the guidelines for using each section?
*Updated April 2016
The customErrors attribute is used when the .net code is throwing an exception (404, 403, 500 etc) and the httpErrors attribute is used when IIS itself is throwing an exception.
/myfakeextensionslessurl --> httpErrors 404
/myfakeaspsx.aspx --> customErrors 404
/myfakeimage.jpg --> httpErrors 404
/throw500.apx --> customErrors 500
/throw500 --> customErrors 500
There are a lot of pitfalls trying to configure this correctly. So if you are looking for a quick example, the best 2 options you have are:
Example 1: Using html pages
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="/Error500.html" redirectMode="ResponseRewrite">
<error statusCode="403" redirect="/Error403.html" />
<error statusCode="404" redirect="/Error404.html" />
<error statusCode="500" redirect="/Error500.html" />
</customErrors>
</system.web>
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly" existingResponse="Auto">
<remove statusCode="403" />
<remove statusCode="404" />
<remove statusCode="500" />
<error statusCode="403" responseMode="File" path="Error403.html" />
<error statusCode="404" responseMode="File" path="Error404.html" />
<error statusCode="500" responseMode="File" path="Error500.html" />
</httpErrors>
</system.webServer>
Example 2: using aspx pages
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="/Error500.html" redirectMode="ResponseRewrite">
<error statusCode="403" redirect="/Error403.aspx" />
<error statusCode="404" redirect="/Error404.aspx" />
<error statusCode="500" redirect="/Error500.aspx" />
</customErrors>
</system.web>
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly" existingResponse="Auto">
<remove statusCode="403" />
<remove statusCode="404" />
<remove statusCode="500" />
<error statusCode="403" responseMode="ExecuteURL" path="Error403.aspx" />
<error statusCode="404" responseMode="ExecuteURL" path="Error404.aspx" />
<error statusCode="500" responseMode="ExecuteURL" path="Error500.aspx" />
</httpErrors>
</system.webServer>
And in the aspx error pages you need to do something like this (example 404 page):
<%
Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true;
%>
Note: Using extension less urls in the customErrors section is not possible!. (without hacks)
One work around is to disable custom errors and let http errors handle the custom page. A friend has created such setup, when I find some time, I will share the code.
Background
A good custom error page will:
Show the real exception when you visit the problem page locally
Show a custom page when you visit the problem page remotely
Will not redirect, but simply show the error page content (because of seo reasons)
Will show the correct status code
So to clarify some options in our config:
<customErrors mode="RemoteOnly". You can specify here: On, Off, RemoteOnly.
On = Always show custom error pages
Off = Always show the real error
RemoteOnly = Show the error locally, but show the custom error page remotely.
So we want RemoteOnly for statement 1
<customErrors redirectMode="ResponseRewrite". You can specify here: ResponseRedirect or ResponseRewrite. The ResponseRedirect mode will redirect the error page to the custom error page. For a link crawler (SEO), this will result in 302 -> 500, but you want the link crawler to get a 500 error.
<httpErrors errorMode="DetailedLocalOnly". This the equivalent of the customErrors mode. Options that you have: Custom, Detailed, DetailedLocalOnly.
A good blog post which helped me a lot is: http://benfoster.io/blog/aspnet-mvc-custom-error-pages
Disclaimer: This is from my experience and not proven fact.
Both are used to define error handling for a website, but different software refers to different config elements.
customErrors are a legacy (backwards compatable) element, used by Visual Studio Development Server (aka. VSDS or Cassini).
httpErrors are the new element which is only used by IIS7.
This highlights the possible problem when developing ASP.NET websites while using VSDS instead of the local IIS.
Also, refer to this post by myself about how to handle error messages with IIS7, if you wish to have full control of the error output.
Summary:
Developing in VSDS - use customErrors
Publishing the site to IIS6 - use customErrors
Publishing the site to IIS7 - use httpErrors.
and if you develop with VSDS but publish to IIS7, then i guess u'll need both.
<customErrors> versus <httpErrors>
<customErrors>
still available in IIS7+
specify custom error pages for requests handled by ASP.NET
only handles requests within the ASP.NET application
static files such as HTML files or directory (“friendly”) URLs are not handled
<httpErrors>
introduced in IIS7
specify custom error pages for requests handled by IIS
handles requests within the ASP.NET application AND/OR handles requests outside the - ASP.NET application *
all files and URLs are handled *
Note: it is no longer necessary to use customErrors
Quoted source: Custom 404 and error pages in ASP.NET (excellent article)
ExecuteURL serves dynamic content such as an .aspx page (the path value has to be a server relative URL):
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Auto" defaultResponseMode="ExecuteURL" >
<remove statusCode="404"/>
<error statusCode="404" responseMode="ExecuteURL" path="/error.aspx" />
</httpErrors>
</system.webServer>
File serves a custom error file, such as a .html page:
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Auto" defaultResponseMode="File" >
<remove statusCode="404"/>
<error statusCode="404" path="404.html" />
</httpErrors>
</system.webServer>
Reference: HTTP Errors (www.iis.net)
for more details, read the www.iis.net link above
Errors section in web config is for providing custom http error handling approach there are two section, one customErrors inside the section system.web and another httpErrors inside the section system.webServer (as given below)
customErrors :
This section was in use before IIS 7 introduced, IIS 6 5 and before fully use this section for handling custom http errors according to http status code.
httpErrors :
IIS 7 and later use this section as well as customErrors section to handle custom http errors based on their file extensions if requested page extension register with ISAPI dll (.aspx, ashx, .asmx, .svc etc) like index.aspx then IIS pick up setting from customeErrors section else it pick up setting from httpErrors (IIS 7 hosted mode must be set as integrated mood not classic)
below are the examples that is for 404 error handling check link :
httperrors vs customerrors in webconfig , iis, asp.net

How can I set the Secure flag on an ASP.NET Session Cookie?

How can I set the Secure flag on an ASP.NET Session Cookie, so that it will only be transmitted over HTTPS and never over plain HTTP?
In the <system.web> element, add the following element:
<httpCookies requireSSL="true" />
However, if you have a <forms> element in your system.web\authentication block, then this will override the setting in httpCookies, setting it back to the default false.
In that case, you need to add the requireSSL="true" attribute to the forms element as well.
So you will end up with:
<system.web>
<authentication mode="Forms">
<forms requireSSL="true">
<!-- forms content -->
</forms>
</authentication>
</system.web>
See here and here for MSDN documentation of these elements.
There are two ways, one httpCookies element in web.config allows you to turn on requireSSL which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.
Edit for clarity:
Put this in <system.web>
<httpCookies requireSSL="true" />
Things get messy quickly if you are talking about checked-in code in an enterprise environment. We've found that the best approach is to have the web.Release.config contain the following:
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<authentication>
<forms xdt:Transform="Replace" timeout="20" requireSSL="true" />
</authentication>
</system.web>
That way, developers are not affected (running in Debug), and only servers that get Release builds are requiring cookies to be SSL.
Building upon #Mark D's answer I would use web.config transforms to set all the various cookies to Secure. This includes setting anonymousIdentification cookieRequireSSL and httpCookies requireSSL.
To that end you'd setup your web.Release.config as:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web>
<httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
<httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
<anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
</system.web>
</configuration>
If you're using Roles and Forms Authentication with the ASP.NET Membership Provider (I know, it's ancient) you'll also want to set the roleManager cookieRequireSSL and the forms requireSSL attributes as secure too. If so, your web.release.config might look like this (included above plus new tags for membership API):
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web>
<httpCookies xdt:Transform="SetAttributes(httpOnlyCookies)" httpOnlyCookies="true" />
<httpCookies xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
<anonymousIdentification xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
<roleManager xdt:Transform="SetAttributes(cookieRequireSSL)" cookieRequireSSL="true" />
<authentication>
<forms xdt:Transform="SetAttributes(requireSSL)" requireSSL="true" />
</authentication>
</system.web>
</configuration>
Background on web.config transforms here: http://go.microsoft.com/fwlink/?LinkId=125889
Obviously this goes beyond the original question of the OP but if you don't set them all to secure you can expect that a security scanning tool will notice and you'll see red flags appear on the report. Ask me how I know. :)
secure - This attribute tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS. This will help protect the cookie from being passed over unencrypted requests. If the application can be accessed over both HTTP and HTTPS, then there is the potential that the cookie can be sent in clear text.