Spring Security - Ensure PreAuthorize PermitAll allows access without custom config class - spring-security

I have a code sample at:
https://github.com/vicsz/pcf-sso-resource-example/blob/master/src/main/java/com/example/pcfssoresourceexample/WebController.java
Is there a way to the get the PreAuthorize PermitAll annotation to allow all access (including no security) ? Specifically WITHOUT writing a custom configuration class extending the WebSecurityConfigurerAdapter ?

Per comment from #dur ... it can't be done.

Related

spring security: what's the best practice for include value in permission?

In spring security, or RBAC, the Authority is described as a string, such as "download-file" means user can download file. If I need to limit user maximum daily download times and assign different values to different user, means the Authority contains dynamic values, how can I do this in spring security?
As you are alluding to there is a difference between authorities (i.e. roles) and permissions. Authorities tend to broadly apply for an application and have no state while permissions tend to be on specific objects and contain state.
This seems more like a domain problem than a permissions problem. Putting the logic into security feels a bit like having a form that must contain a valid email and checking the email format in security. I'd consider moving the logic outside of the security code.
If you really want to do this with Spring Security, I'd use a custom Bean that performs the check:
#Component
public class Download {
public boolean isAlowedForUser(Authentication authentication) {
// ...
return result;
}
public boolean isAllowedForCurrentUser() {
return isAllowedForUser(SecurityContextHolder.getContext().getAuthentiation());
}
}
Then you can autowire the Bean into your code and check the permission by invoking the code. If you prefer, you can also integrate into Spring Security's method security to perform the checks. To enable it you need to specify #EnableGlobalMethodSecurity(prePostEnabled = true) at the top of one of your configuration classes. Then you can use something like this on a Spring managed Bean:
#PreAuthorize("#download.isAllowedForCurrentUser()")
public void downloadFile(String fileName) {
Please refer this link
Spring Boot : Custom Role - Permission Authorization using SpEL
You can add new permission , like "DOWNLOAD_FILE" and authenticate if the current user has that permission using -
#PreAuthorize("hasPermission('DOWNLOAD_FILE')")
You can also limit access for Roles as well
#PreAuthorize("hasRole('ADMIN') and hasPermission('DOWNLOAD_FILE')")

#Post Filter is not filtering the method returned collection using acl and oauth spring security

I m trying to integrate both Oauth security and acl spring security.
Instead of below oauth expression handler
<sec:global-method-security pre-post-annotations="enabled" proxy-target- class="true">
<sec:expression-handler ref="oauthExpressionHandler" />
</sec:global-method-security>
I used the acl expression handler following configuration
as explained in http://krams915.blogspot.in/2011/01/spring-security-3-full-acl-tutorial_30.html.
I am able to make acl entries in table.But while using the #PostFilter the objects returned by the method are not getting filtered using acl permission.
Can some one please help
In my configuration I made two mistakes which made #PostFilter inactive.
As told by Denim in the above comments I loaded component scan twice once by dispatcher servlet and again i loaded dispatcher servlet xml using context loader listener.With this change i was able to detect the annotation in the package where i declared the context i,e webapplication module.but in my service module the annotation was not being detected.
2 the issue in my service layer is
I had my service class as below and applied annotation as below
#Service("a")
#Transactional
Class A{
public List<Users> getUsers() {
getNames();
}
#PostFilter("hasPermission(filterObject,'edit')")
public List<Users> getNames() {
}
The annotation will not be considered as both the methods will be in the same proxy can refer
the following url
Spring AOP not working for method call inside another method

Spring OAuth2 - custom "OAuth Approval" page at oauth/authorize

what is recommended way to create custom pages OAuth Approval page:
I have to completely override the stuff on the page, need to add styles, branding etc. What is the right way to achieve that? Where could I see the source of the default page to use it as a starting point?
I also need to override the /login page but I think the approach of overriding it is going to be pretty much the same.
The recommended way is to provide a normal Spring MVC #RequestMapping for the "/oauth/confirm_access". You can look at WhitelabelApprovalEndpoint for the default implementation. Don't forget to use #SessionAttributes("authorizationRequest") in your controller.
In addition to #DaveSyer's answer, which should work for the most of the cases. Sometimes based on configuration and customization the aforementioned method may not work, if Framew‌orkEndpointHandlerMa‌pping from Spring Security OAuth package has higher order than RequestMappingHandlerMapping of your application. If this is the case, then servlet dispatcher will never reach you mapping and will always show the default page.
One way to fix it is to change the order of mappers, given that Framew‌orkEndpointHandlerMa‌pping's order is Order.LOWEST_PRECEDENCE - 2.
Another way is to set the approval page to a custom URL, not mapped by Framew‌orkEndpointHandlerMa‌pping, thus servlet dispatcher will reaches you application's mapping
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthorizationEndpoint authorizationEndpoint;
#PostConstruct
public void init() {
authorizationEndpoint.setUserApprovalPage("forward:/oauth/custom_confirm_access");
authorizationEndpoint.setErrorPage("forward:/oauth/custom_error");
}
}
With such a configuration mappings of /oauth/custom_confirm_access and /oauth/custom_error will be used as a confirmation page and an error page respectively.

Checking whether the user authenticated using spring security inside a filter

I'm trying to do this in my groovy class which is in src directory of my grails application.
Its an Filter. The class looks like this :
class Proxy implements Filter {
}
Inside the init method I'm getting the springSecurityService bean using :
GrailsApplication application = org.codehaus.groovy.grails.commons.ApplicationHolder.getApplication()
springSecurityService = application.getMainContext().getBean("springSecurityService")
And inside my doFilter I'm trying to find whether the user is been authenticated or not. I tried:
springSecurityService.isLoggedIn()
but its always returning false.
Where I'm making the mistake?
Thanks in advance.
Is it possible the order of your filters are incorrect? Your custom Filter would need to be invoked after the Spring Security Filter. If you perform new Exception().printStackTrace() inside your filter, do you see the SecurityContextPersistenceFilter in the stack? If not, then you need to change your Filter (Proxy) to be after the springSecurityFilterChain.
Try to use SecurityContextHolder
SecurityContextHolder.getContext().getAuthentication()
(but this is Java; I'm sure there is something similar you can find)

Access/check Spring Security hierarchical roles programmatically

In my Grails project I defined multiple hierarchical roles using the Spring Security plugin e.g. ROLE_USER > SOME_OTHER_ROLE. When securing controller methods using the #Secured annotation it works just fine. However, I also would like to check the role programmatically in my code for one use case. Using the following approach I always get a false even though the user inherits the role through hierarchical role definition:
request.isUserInRole('SOME_OTHER_ROLE')
Also the following calls never directly return the inherited roles:
SecurityContextHolder.context?.authentication?.authorities
springSecurityService.getPrincipal().getAuthorities()
Is there a way of checking if the user also has the inherited role?
This seems like a bug (or at least an omission) in SecurityContextHolderAwareRequestWrapper which adds a request wrapper to implement the isUserInRole method.
You can use the roleVoter bean's extractAuthorities method. Add a dependency injection for it (def roleVoter) and then call
def allRoles = roleVoter.extractAuthorities(
SecurityContextHolder.context.authentication)

Resources