w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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

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

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 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

Controlling security on model updates in RESTful Spring MVC / HATEOS
Two possibilities comes to my mind: validation (@Valid) binder configuration (@InitBinder) You can validate the incoming object and check for such changes. Or you can set-up WebDataBinder#setAllowedFields within your @InitBinder method based on user authorities. The latter one would be probably the easiest way. However instead of returning validation error your application will ignore the fields completely.

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

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

How to implement custom authentication in Spring Security 3?
In most cases when only using usernames and passwords for authentications and roles for authorisation, implementing your own UserDetailsService is enough. The flow of the username password authentication is then generally as follows: A spring security filter (basic authentication/form/..) picks up the username and password, turns it into an UsernamePasswordAuthentication object and passes it on to the AuthenticationManager The authentication manager looks for a candidate provider which can handle UsernamePasswordtokens, which in this case is the DaoAuthenticationProvider and passes the token along for authentication The authentication provider invokes the method loadUserByUsername interface and throws either a UsernameNotFound exception if the user is not present or returns a UserDetail

Categories : Spring

Authenticate user for secure spring service with CAS RESTful API ticket
After comparing with my study demo, I think you missing the following configuration : <bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties"> ... <property name="authenticateAllArtifacts" value="true"/> </bean> See Spring Security Reference Documentation 22.3.4 Proxy Ticket Authentication.

Categories : Misc

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 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 and nested FilterChainProxy writing SAML Service Provider
I was not able to get any definitive statement of this, but the problem appears to be with Spring Security 3.1.1 not playing well with Spring SAML or indeed any implementation that uses the same kind of nested FilterChainProxys. It appears FilterChainProxy was completely rewritten for 3.1.1. When I looked at the latest release (3.1.4), I noticed that there is a check in the finally clause that only clears the SecurityContextHolder ("SEC-1950") IF it is the first invocation of the filter. Thus, upgrading spring security to 3.1.4 solved the problem.

Categories : Spring

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 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

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 JSF integration: how to inject a Spring component/service in JSF managed bean?
@ManagedBean vs @Controller First of all, you should choose one framework to manage your beans. You should choose either JSF or Spring (or CDI) to manage your beans. Whilst the following works, it is fundamentally wrong: @ManagedBean // JSF-managed. @Controller // Spring-managed. public class BadBean {} You end up with two completely separate instances of the very same managed bean class, one managed by JSF and another one managed by Spring. It's not directly clear which one would actually be used in EL when you reference it as #{someBean}. If you have the SpringBeanFacesELResolver registered in faces-config.xml, then it would be the Spring-managed one, not the JSF-managed one. If you don't have that, then it would be the JSF-managed one. Also, when you declare a JSF managed bean spec

Categories : Spring

How to pass user and password to Spring REST service with Spring RESTTemplate
it would help if you posted the method signature from the server side. how are you doing your authentication? here's a get example. post would be the same but using postForObject() String result = restTemplate.getForObject("http://127.0.0.1:8080/springmvc-rest-secured-test/json/{user}/{password}", String.class, "user", "pass");

Categories : Spring

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

How to call spring roo service in spring data JPA entity?
You can create one util class that will have a static reference to the ApplicationContext, here is a code example that I use in my project(cant remember where I copied this class from): package yourpage; /** * Wrapper to always return a reference to the Spring Application Context from * within non-Spring enabled beans. Unlike Spring MVC's * WebApplicationContextUtils we do not need a reference to the Servlet context * for this. All we need is for this bean to be initialized during application * startup. */ public class SpringApplicationContext implements ApplicationContextAware { private static ApplicationContext CONTEXT; /** * This method is called from within the ApplicationContext once it is done * starting up, it will stick a reference to itself into this bea

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

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

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

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

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

How can I implement compression of a WCF RESTful (JSON) Service in C# with interoperabiility?
you can change your web.config file to solve this problem. change httpRuntime <httpRuntime maxRequestLength="10240" executionTimeout="1000" /> here, maxRequestLength: Indicates the maximum file upload size supported by ASP.NET. This limit can be used to prevent denial of service attacks caused by users posting large files to the server. The size specified is in kilobytes. The default is 4096 KB (4 MB). executionTimeout: Indicates the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

Categories : Json

Spring MVC-Spring security
You don't need to do specify mvc-dispatcher-servlet.xml in contextConfiglocation <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/mvc-dispatcher-servlet.xml, /WEB-INF/spring-security.xml </param-value> </context-param> Its solves your problem

Categories : Spring

Spring MVC restful path
When referring the path variable use something like this @PathVariable("productId") int productId This enclosed variable name is same as the variable name in the request mapping @RequestMapping(value="/{productId}", method = RequestMethod.GET)

Categories : Spring

Spring REST service.. How do I secure REST calls I am making in Spring MVC
Use HTTPS Use Spring Security with HTTP-header-based authentication Official examples: https://github.com/SpringSource/spring-security/tree/master/samples

Categories : Spring

how to create restful web services using spring 3.0?
I think it's better to start from scratch. Just create a project in your IDE and add the jars and configurations step by step. It's not easy to read hundreds of lines of XML written by others from the start, at least for me. Here is a very simple tutorial, hope it helps.

Categories : Spring

RESTful API with Spring MVC and GWT and overlay types
The REST response can be consumed by any client and not specifically one client. If I understand your question correctly, you want to build the logic of marshalling and unmarshalling inside your REST API. Ideally it violates Single Responsibility Principal. You might need to change the mapping logic if the service changes so you are touching two different aspects of an API where as only one component requires change. Also, the REST API should ideally be designed to be client agnostic. It is your specific requirement to translate them to POJO but another client might want to consume it as simple plain JSON. If you provide an overlay type, your code will be quite loosely coupled.

Categories : Java

Post data Spring web services Restful
If you want to call this controller in a RESTful manner, you have to annotate the solicitud parameter as @RequestBody. Second, you have to have the Jackson libraries in you classpath so Spring can pick them up and use them for unmarshalling the object. If you use Maven, use these dependencies: <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.12</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.12</version> </dependency> BTW, why do you have to serialize the HTML form and sent it across?

Categories : Java

can anyone tell me how to create RESTful web services in spring with annotations
http://www.mkyong.com/spring-mvc/spring-3-rest-hello-world-example/ is a very good and useful tutorial. It goes through how to set up the Spring MVC project from scratch using Maven as your build tool and then it goes through a Spring MVC controller that uses the URL to perform REStful Web Services. Although it may seem small, the tutorial is very useful in getting you started and provides you with a platform to carry out more complex tasks. The following reference may be useful as a reference. http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch18s02.html

Categories : Rest

Getting 404 requested resource not available in spring restful web services
I beleive you need to put the RequestMapping for your method with a /. Something like this: @RequestMapping(value = "/", method = RequestMethod.GET) public String getHello() { return "hello world"; }

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

How to set accept media type in RestTemplate (Spring restful client)
If the Rest Service is producing only XML, then I don't think you will be able to accept it as JSON. In that case what you need to do is add the MediaType as "application/json" in the Rest Service, along with the existing xml response. For e.g in Spring Restful Service the annotation would be @RequestMapping(value = "/myurl", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) If the Rest Service is producing Json and Xml, then in the rest client you need to do : ResponseEntity<YourClass> apiResp = restTemplate.exchange(url, HttpMethod.GET, request, YourClass.class); YourClass output=apiResp.getBody();

Categories : Java

Trying to get an Android annotations spring RESTful client api working, couple of problems
I'm not known with the library you're using (annotations, spring) but it seems to me that you are struggling with parsing the success = true because that is not supposed to be in the JSON. The JSON should preferably represent a class in your app 1on1 so you can easily map that into an object. Communication between your app and the webservice, regarding the status of requests should go into the headers. Like this you can check a request's headers, before parsing the JSON.

Categories : Android



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