w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Spring 3.2: Filtering Jackson JSON output based on Spring Security role
Althou it is possible to write custom JSON processing filter (e.g. based on JSON Pointers), it will be a little bit complex to do. The simplest way is to create your own DTO and map only those properties, which the user is authorized to get.

Categories : Spring

Spring Security Without Role-Base Using Database
Have you tried to do it in the spring security xml configuration file : <security:http auto-config="true" use-expressions="true"> <security:intercept-url pattern="/login" access="permitAll" /> <security:intercept-url pattern="/registration" access="permitAll" /> <security:intercept-url pattern="/**" access="isAuthenticated()" /> ... </security:http>

Categories : Database

Validate test user with spring security against database
I see <password-encoder hash="md5" /> in your configuration. It means you are using md5 to encode password in Authentication-Provider. So you must encode "test" using md5 in your CustomUserDetailsService too: new User("test", "encoded_password", getAuthorities(1));

Categories : Java

spring security filter chain url pattern matching
Without the <intercept-url> tag within <http>, this declaration basically says that anyone can access any resource under the /restful/** path. The <intercept-url> here restricts access to users who have been assigned the ROLE_REMOTE role, which is quite different. <intercept-url> patterns are relative to the enclosing <http> element pattern, so nothing outside the /restful/** path will be intercepted by this declaration. The typical pattern is that you will have one <http> element with several <intercept-url> elements within targeting different URL patterns. Additional <http> elements can be useful when you want authentication and access control to behave differently, for example session management or authentication failure handlers for RE

Categories : Spring

Spring security: A universal match pattern ('/**') is defined before other patterns in the filter chain, causing them to be ignored.
The problem was in the regex of classpath in the context-param. <param-value> classpath:**/sampler-context.xml classpath:**/sampler-security.xml </param-value> Changing it to <param-value> classpath*:sampler-context.xml classpath*:sampler-security.xml </param-value> solves this problem.

Categories : Spring

Spring Security @RolesAllowed Works but @Secured gives me AccessDeniedException in Spring 3.2 with Spring Security 3.1
Try to use a security role with a name that ends with ROLE From Spring Security Reference: RoleVoter The most commonly used AccessDecisionVoter provided with Spring Security is the simple RoleVoter, which treats configuration attributes as simple role names and votes to grant access if the user has been assigned that role. It will vote if any ConfigAttribute begins with the prefix ROLE_. It will vote to grant access if there is a GrantedAuthority which returns a String representation (via the getAuthority() method) exactly equal to one or more ConfigAttributes starting with the prefix ROLE_. If there is no exact match of any ConfigAttribute starting with ROLE_, the RoleVoter will vote to deny access. If no ConfigAttribute begins with ROLE_, the voter will a

Categories : Spring

Eclipse Spring Security Warning 'unable to load namespacehandler'
All xsd schemas that you can use are stored inside some jar file. In this case it will be spring-security-config-3.2.0.M2.jar. Open it in Eclipse (Project Explorer -> Your project -> Java Resources -> Libraries -> Maven Dependencies -> spring-security-config-3.2.0.M2.jar). You can find the list of available schemas in META-INF/spring.schemas file. Normally all shcemas are in org.springframework.security.config package (for example org/springframework/security/config/spring-security-3.1.xsd). Make sure that you use one of schemas available there. If it is not the case then update your security xml file. Othervice if you can find corresponding file then it is the problem with Eclipse (Project -> Clean).

Categories : Java

Spring Security UI plugin for Grails creates neither spring-security-ui.css nor i18n files
Try extracting the files from the directory you need, from the version you need https://github.com/grails-plugins/grails-spring-security-ui/tree/master/grails-app/assets/stylesheets https://github.com/grails-plugins/grails-spring-security-ui/tree/master/grails-app/i18n

Categories : Grails

Making a form pattern using the pattern attribute to validate an email
You will need to use regex to validate the email address. I suggest you look here if you don't know about regular expressions. The expression for validating an email is this: /^[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,4}$/ You will have to validate it using JavaScript regex. Check that out here.

Categories : HTML

Spring Security 3.1.x & JSF 2.0 : " BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains' "
I would start by checking your classpath (look in the lib directory of your WAR file) and make sure you don't have different Spring jars in there. It's not uncommon for maven to pull in transitive dependencies from some dependency and cause you to end up with Spring 3.0.x and Spring 3.1.x jars at once. You can avoid this by adding exclusions to your pom, or more simply by explicit versions each Spring jar you need. Then make sure you are using up-to-date versions of both Spring Security and Spring. Note that Spring and Spring Security are separate projects with independent version numbers. There's no reason why you can't be using Spring 3.2.3 with Spring Security 3.1.4, for example, but you should have the latest minor version of whichever release you choose.

Categories : Java

Spring security override specific message : Your login attempt was not successful, try again. - not found under org.springframework.security
Actually it is easy resolvable by custom login form. Since it won't display any of sf error messages we can pass error param back after processing. Consequently simply check for this param and add whatever text message you like. authentication-failure-url="/login?error=true" then in our new login page simply add something like: <c:if test="${error}"> <s:message code="AbstractUserDetailsAuthenticationProvider.badCredentials"/></c:if> where you can use any message code from your resource bundle.

Categories : Spring

Providing security for Restful Web Services into existing Spring security 3.1
You should use two http tags. One for your web application and the other one for your REST API. Let's say, you can use an entry point web/** for your web app and an entry point api/** for your REST API. You propaply want to secure your API with HTTP Basic, so your web app should work with form login (that uses java session) and your REST API with HTTP Basic authentication. REST APIs are better secured with OAuth 2, but depending on size or audience of your application would be overkill.

Categories : Spring

Java Web Application Role Only Security
Ok, finally I've found a solution that actually is described in this article in the 'Using Identity Assertion for Web Application Authentication' section: I've added these lines into the web.xml: <login-config> <auth-method>CLIENT-CERT</auth-method> </login-config> and that worked.

Categories : Java

Is it possible to run a spring webmvc webapp with spring security in one spring container?
Short answer Remove the /WEB-INF/myapp-servlet.xml from the contextConfigLocation context param. Long Answer The ContextLoaderListener creates a root application context based on the configuration files defined in the contextConfigLocation and loads it into the ServletContext before any Servlet is initialized. The DispatcherServlet at the same time, will create a child application context with the specified configuration. You are not explicitly specifying any bean definition file, so by convention it will take /WEB-INF/appName-servlet.xml (/WEB-INF/myapp-servlet.xml in your case, which by chance exists). It happens that both your root application context and your child application context will have some common beans (duplicates, because they load the same configuration file). You hav

Categories : Java

Spring security 3.2.0 > deprecated
I'm not sure if this answer can help you. However, the warning message generated by IDE is not a big problem because you did not use the deprecated method. I'm using spring security too and I also can see the same warning message but the service is working perfectly. I'm sorry if the answer is not you wanted.

Categories : Spring

Spring Security - 'global-method-security' does not work
Looks like you should follow with recomendation from Spring Security Reference Manual: The annotated methods will only be secured for instances which are defined as Spring beans (in the same application context in which method-security is enabled). A similar problem is discussed here: How can <global-method-security> work on my controller by Spring-Security? See the last post.

Categories : Java

SonataUser - Custom Voter with Role Security
After hours of searching, I noticed that the object received is always NULL (get_class(NULL) returns the current class). After days of seeking, It turns out that, as opposed to the ACL handler, the default implementation of the Role handler doesn't pass the current object to isGranted() I had then to extend it. See a nice monologue in my github issue for more detail.

Categories : Security

Setting a default role in flask-security
If you have already created a role "User", You can add that role to the user when you create/register the user. def create_user(): db.create_all() user = user_datastore.create_user(email='my@email.com', password='password') default_role = user_datastore.find_role(name="User") user_datastore.add_role_to_user(user, default_role) db.session.commit()

Categories : Python

Flask-security add role to user (MongoEngine)
May be I am missing something but you need to commit the changes, right ? user = user_datastore.find_user(email=flask.request.args.get('email')) role = user_datastore.find_role(flask.request.args.get('role')) result = user_datastore.add_role_to_user(user, role) # to save in database, you must commit (assuming 'db' is the object) db.session.commit()

Categories : Python

AngularJS and Spring Security. How to handle AngularJS Urls with Spring Security
I wrote a little sample application that illustrates how to integrate AngularJS with Spring Security by exposing the session id as an HTTP header (x-auth-token). The sample also provides some (simple) authorization (returning the roles from the server) so that the client AngularJS application can react to that. This is of course primarily for user-experience (UX) purposes. Always make sure your REST endpoints have property security. My blog post on this is here.

Categories : Spring

Sonata User - Role security Access denied
Ok I didn't see I had also ROLE_SONATA_ADMIN_USER_* listed in admin, I don't understand why. So I had to set ROLE_EDIT_USER: - ROLE_SONATA_ADMIN_USER_LIST - ROLE_SONATA_ADMIN_USER_EDIT instead Sometimes Symfony seems to me so complicated for simple things... I spend 10x less time configuring same things with Django for example.

Categories : Symfony2

How to get the security role with the user id in Websphere Application server
As for the servlet/EJB API, you can only check if a user is in a certain role, but you cannot get the list of assigned roles. If the user you get in the request header is authenticated by server A, you can call HttpServletRequest.isUserInRole against a list of known role names. In your case the user is probably not authenticated by server A (because there is a trust), so this is not possible - there is no official API. I am not aware of a WebSphere specific API. Options (all of these are only applicable, if there is really a trust) Server B could pass the role(s) in a request header as well Implement an EJB/web service etc. on server B, so that server A can query for the roles of a given user If the roles are managed by an external system (LDAP etc.), you could get the roles from that

Categories : Security

What is the difference between Security Token Service and OAuth 2.0 "Authorization Server" role?
No, the WIF classes don't support the OAuth2 framework. Writing one from scratch is not trivial. The Thinktecture AuthorizationServer is an open source OAuth2 implementation that might get you started: http://thinktecture.github.io/Thinktecture.AuthorizationServer/

Categories : Security

Spring security session management and Spring MVC view resolver error
You are redirecting to the jsp not the mapped url. session management tag should be : <session-management invalid-session-url="/login?error=sessionExpired" session-authentication-error-url="/login?error=alreadyLogin"> <concurrency-control max-sessions="1" expired-url="/login?error=sessionExpiredDuplicateLogin" error-if-maximum-exceeded="false"/> </session-management>

Categories : Spring

Including "spring-security-config" into classpath makes spring hang with NoClassDef at "Aware"
Spring security has a different version scheme with spring core (I believe historically they are maintained by different organization). I suggest you don't use generic ${spring.version} variable. Read the documentation of what minimum spring core is required for corresponding spring security version If you believe you've got all the versioning correct, next possible cause is your maven configuration itself. Often you did not realize you've set your settings to NOT lookup from central repository / your organization internal maven repo (nexus) has a stale index not having latest version of spring artifacts

Categories : Spring

Redirect to the original URL after signin using Spring Social, Spring security?
Have you actually tried it to see if it works? Spring security does this automatically. If you are an anonymous user and attempt to access a resource that requires a certain permission, spring security will store the attempted URL and redirect you to the login page. After successful login it fetches the attempted URL back and redirects you there.

Categories : Java

Spring security- org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains'
Looking at the stacktrace information it appears as if you have conflicting framework jars in your classpath. When using maven use mvn dependency:tree to figure out which dependencies get used, I suspect that there is an older spring-beans.jar in your classpath.

Categories : Java

Spring Bean not found for Spring Security RememberMe?
Cannot convert value of type [groovy.util.ConfigObject] to required type [int] for property 'tokenLength' This suggests to me that you don't have a grails.plugins.springsecurity.rememberMe.persistentToken.tokenLength property set in your grailsApplication.config - when you ask a ConfigObject for a non-existent key what it returns to you is a new empty ConfigObject.

Categories : Java

Spring MVC + Spring Security login with a rest web service
you can define a custom pre-auth filter by extending AbstractPreAuthenticatedProcessingFilter. In your implementation of getPreAuthenticatedPrincipal() method you can check if cookie exists and if it exists return cookie name is principal and cookie value in credentials. Use PreAuthenticatedAuthenticationProvider and provide your custom preAuthenticatedUserDetailsService to check if cookie is vali, if its valid also fetch granted authorities else throw AuthenticationException like BadCredentialsException For authenticating user using username/password, add a form-login filter, basic-filter or a custom filter with custom authentication provider (or custom userdetailsService) to validate user/password In case cookie exists, pre auth filter will set authenticated user in sprin

Categories : Spring

Spring MVC controller inheritance with spring security
I know it's a year later, but I had the same problem and figured out a possible solution for this. It is not 100% annotation based, but works and is somewhat elegant The abstract superclass: @PreAuthorize("hasAnyRole(this.roles)") public abstract class DataController<E extends PersistentEntity> { protected abstract E getEntity(String id); protected abstract String[] getRoles(); @RequestMapping(value="/view/{id}", method=RequestMethod.GET) public String view(@PathVariable("id") String id, ModelMap map) { E ent = getEntity(id); map.put("entity", entity); return "showEntity"; } } On the subclass you simply implement getRoles() to return an array of roles that are required to access this class. @PreAuthorize is another way to check authe

Categories : Java

Spring MVC Spring Security and Error Handling
The reason is right there, in the DispatcherServlet class; it sends error response without bothering to call exception handler (by default). Since 4.0.0.RELEASE this behaviour can be simply changed with throwExceptionIfNoHandlerFound parameter: Set whether to throw a NoHandlerFoundException when no Handler was found for this request. This exception can then be caught with a HandlerExceptionResolver or an @ExceptionHandler controller method. XML configuration: <servlet> <servlet-name>rest-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>throwExceptionIfNoHandlerFound</param-name> <param-value>true</param-value>

Categories : Spring

Access Spring MVC Service From Spring Security
I'm not sure what's your setup or what you're trying to do but I'll try to help you based on a basic spring-security setup. First of all, your UserService should implement UserDetailsService In your web.xml <!-- Context Configuration locations for Spring XML files --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:META-INF/spring/some-application-service.xml /WEB-INF/security.xml </param-value> </context-param> /WEB-INF/security.xml <!-- Assuming UserService is in com.sample.security package. --> <context:component-scan base-package="com.sample.security"/> <authentication-manager> <authentication-provider user-service-ref="userService" /> </

Categories : Java

Spring Roo Get role of current logged user
If you are including the Spring JSTL tag libs, you can do something like: <sec:authorize access="hasRole('supervisor')"> It works like an "if" that renders the stuff inside the tag when the given user has the specified role. There are a couple other access methods you can use other than hasRole() as well. Docs for the JSTL tags are here.

Categories : Spring

Spring is returning proper authority/role
I have solved the issue changing target URL <security:form-login login-page="/krams/auth/login" authentication-failure-url="/krams/auth/login?error=true" default-target-url="/krams/main/test"/>

Categories : Spring

how to validate the pattern in form submit
One route you can go uses mask.js - In your case you can have it force the user to input their data in the proper format, pre-populate the '.' characters in the IP, and stop the user from entering non-numeric values. Mask.js And here is a fiddle - http://jsfiddle.net/QF9Lz/2/ click in the textbox, you'll see a formatting mask appear and you will only be able to enter numeric values in the format you specified. So, once you include mask.js in the head, you can initialize the input mask like this: $(document).ready( function() { $('#ip').mask('999.999.9.999'); });

Categories : HTML

It is ok to delete using GET if im using Spring MVC with Spring security?
What do you mean "is it ok"? It will work, yes. It would be clearer to use the actual DELETE verb. You can use Spring's HiddenHttpMethodFilter to achieve this, while securing the URL with Spring Security using something like this: <sec:intercept-url pattern="/entity/**" method="DELETE" access="hasRole('ROLE_ADMIN')" />

Categories : Spring

Iintegrate Spring Security into spring mvc 3.2
Problem with spring-security-javaconfig is that it is not yet released. In one of our application we have configured security in @Configuration manually. But I know a thing or two about Spring's security inner workings so that was quite easy for me. I can imagine it might not be so easy for a non-experienced user. I would suggest you to configure security via XML. It is easier, well documented and it just works. You can import security XML configuration via @ImportResource from your @Configuration class. Registering DelegatingFilterProxy with a correct name springSecurityFilterChain from you WebApplicationInitializer should be also piece of cake.

Categories : Spring

MVC repository pattern, how to security trim?
Create a base class that converts each query to one where the permissions are checked and let your repository classes inherit from that. Something like this: public interface ISecuredEntity { IEnumerable<string> Permissions { get; } } public class Address : ISecuredEntity { public IEnumerable<string> Permissions { get; set; } } public class AddressRepository : SecureRepositoryBase<Address>, IAddressRepository { private AISDbContext context = new AISDbContext(); public IQueryable<Address> GetAddresses() { return base.RetrieveSecure(context.Address, CURENTUSER); } } public abstract class SecureRepositoryBase<T> where T : ISecuredEntity { public IQueryable<T> RetrieveSecure(IQueryable<T> entities, IUser c

Categories : C#

Where to validate variables (to make it a well designed pattern)?
Validate at the very first point when you are receiving $_GET at the entry level so that you are sure for the below code at later stage as well- // Validate $_GET['some_string'] HERE $result = do_something($_GET['some_string']); If you validate here - function do_something($string) { // Validate $string here? } then there is a possibility that u miss the validation and it will open a loop hole in the code as validation is available only to the method this time. If you are setting some values for the database, it is a good practice to double check the data and make it safe from code injections.

Categories : PHP

Conflicts with Spring 3.2.1.RELEASE and spring security 3.1.3.RELEASE. java.lang.NoSuchFieldError: NULL
It is visible from your dependency:list that you have incorrect version of spring-expression dependency: org.springframework:spring-expression:jar:3.0.7.RELEASE:compile Just add the following to your POM: <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>3.2.1.RELEASE</version> </dependency> </depdendencies> </dependencyManagement> You can alter the definition of transitive dependencies via dependencyManagement like this.

Categories : Spring



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.