首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >使spring透明地为用户工作

使spring透明地为用户工作
EN

Stack Overflow用户
提问于 2015-05-08 02:28:42
回答 1查看 956关注 0票数 1

我开发了一个spring应用程序(带有REST服务),它使用spring数据库获得用户凭据的oauth2进行保护。工作很好,我可以使用Oauth access_token访问受保护的资源。问题是如何使processus透明地为用户工作,让我解释一下,对于我来说,我做了以下步骤来使它工作:

  1. 我尝试从/oauth/令牌获取access_token,如下所示: localhost:8080/rsoneApp/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=admin&password=adminpass
  2. 我通过发送上面生成的access_token请求受保护的资源: localhost:8080/rsoneApp/v1/Books/getAll?access_token=b88564a5-54a2-4afa-bf4f-85aefd58412

但是,正如您所看到的,我应该获取access_token,并将其作为参数复制/通过,以获得受保护的资源。但是对于应该具有包含用户名和密码的视图的用户,

它应该如何工作,应该在哪里存储access_token和刷新令牌,以及如何从最终用户端透明地使用它们?

有人能给我一个使用数据库的例子来说明整个过程吗?这里堆满了!

security-config.xml

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd ">

    <!--<bean name="configClass" class="com.rsone.config.PersistenceConfig" /> -->
    <!-- This is default url to get a token from OAuth -->
    <http pattern="/oauth/token" create-session="stateless"
          authentication-manager-ref="clientAuthenticationManager"
          xmlns="http://www.springframework.org/schema/security">
        <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
        <anonymous enabled="false" />
        <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
        <!-- include this only if you need to authenticate clients via request
         parameters -->
        <custom-filter ref="clientCredentialsTokenEndpointFilter"
                       after="BASIC_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>

    <!-- This is where we tells spring security what URL should be protected
     and what roles have access to them -->
    <http pattern="/v1/**" create-session="never"
          entry-point-ref="oauthAuthenticationEntryPoint"
          access-decision-manager-ref="accessDecisionManager"
          xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false" />
        <intercept-url pattern="/v1/test" access="ROLE_APP" />
        <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
    </http>


    <bean id="oauthAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="test" />
    </bean>

    <bean id="clientAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="test/client" />
        <property name="typeName" value="Basic" />
    </bean>

    <bean id="oauthAccessDeniedHandler"
          class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

    <bean id="clientCredentialsTokenEndpointFilter"
          class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
        <property name="authenticationManager" ref="clientAuthenticationManager" />
    </bean>

    <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
          xmlns="http://www.springframework.org/schema/beans">
        <constructor-arg>
            <list>
                <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
                <bean class="org.springframework.security.access.vote.RoleVoter" />
                <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
            </list>
        </constructor-arg>
    </bean>

    <authentication-manager id="clientAuthenticationManager"
                            xmlns="http://www.springframework.org/schema/security">
        <authentication-provider user-service-ref="clientDetailsUserService" />
    </authentication-manager>


    <!-- This is simple authentication manager, with a hardcoded user/password
     combination. We can replace this with a user defined service to get few users
     credentials from DB -->
    <authentication-manager alias="authenticationManager"
                            xmlns="http://www.springframework.org/schema/security">
        <authentication-provider>

            <jdbc-user-service data-source-ref="dataSource"
                                   users-by-username-query="
              select login,password,'true'
              from users u where u.login=?"
                                   authorities-by-username-query="
              select u.login,ur.authority from users u,user_roles ur where u.id=ur.user_id and u.login=?" />

        </authentication-provider>
    </authentication-manager>

    <bean id="clientDetailsUserService"
          class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <constructor-arg ref="clientDetails" />
    </bean>


    <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
        <constructor-arg ref="dataSource" />
    </bean>

    <!-- This is where we defined token based configurations, token validity
     and other things -->
    <bean id="tokenServices"
          class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
        <property name="tokenStore" ref="tokenStore" />
        <property name="supportRefreshToken" value="true" />
        <property name="accessTokenValiditySeconds" value="120" />
        <property name="clientDetailsService" ref="clientDetails" />
    </bean>
    <!-- the old
    <bean id="userApprovalHandler"
          class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
        <property name="tokenServices" ref="tokenServices" />
    </bean> -->

    <bean id="userApprovalHandler"
          class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
        <property name="tokenStore" ref="tokenStore"/>
        <property name="requestFactory" ref="oAuth2RequestFactory"/>
    </bean>

    <oauth:authorization-server
            client-details-service-ref="clientDetails" token-services-ref="tokenServices"
            user-approval-handler-ref="userApprovalHandler" token-endpoint-url="/oauth/token">
        <oauth:authorization-code />
        <oauth:implicit />
        <oauth:refresh-token />
        <oauth:client-credentials />
        <oauth:password />
    </oauth:authorization-server>

    <oauth:resource-server id="resourceServerFilter"
                           resource-id="test" token-services-ref="tokenServices" />

    <oauth:client-details-service id="clientDetails">
        <!-- client -->
        <oauth:client client-id="restapp"
                      authorized-grant-types="authorization_code,client_credentials"
                      authorities="ROLE_APP" scope="read,write,trust" secret="secret" />

        <oauth:client client-id="restapp"
                      authorized-grant-types="password,authorization_code,refresh_token,implicit"
                      secret="restapp" authorities="ROLE_APP" />

    </oauth:client-details-service>

    <sec:global-method-security
            pre-post-annotations="enabled" proxy-target-class="true">
        <!--you could also wire in the expression handler up at the layer of the
         http filters. See https://jira.springsource.org/browse/SEC-1452 -->
        <sec:expression-handler ref="oauthExpressionHandler" />
    </sec:global-method-security>

    <oauth:expression-handler id="oauthExpressionHandler" />
    <oauth:web-expression-handler id="oauthWebExpressionHandler" />

    <!-- added -->
    <bean id="oAuth2RequestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
        <constructor-arg ref="clientDetails"/>
    </bean>

</beans>

在我的数据库中有用户表和user_roles表

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
user     user_roles
----     ------------
id,..    id,user_id,role
EN

回答 1

Stack Overflow用户

发布于 2015-05-26 01:29:29

有和你一样的问题,我希望会有一个人去付出一切。在我的例子中,当我尝试使用url: localhost: 8080 / oauth / token grant_type = client_id restapp =& username = admin & password访问/ oauth /令牌时?

不起作用

这是我的xml配置文件:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/security/oauth2
            http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/security 
            http://www.springframework.org/schema/security/spring-security-3.2.xsd">



<global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled"  secured-annotations="enabled" proxy-target-class="true">
    <expression-handler ref="oauthExpressionHandler" /> 
    </global-method-security>


        <!-- Definition of the Authentication Service -->
    <http pattern="/oauth/token" create-session="stateless" 
        authentication-manager-ref="clientAuthenticationManager"> 
        <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/>   
        <anonymous enabled="false"/>  
        <http-basic entry-point-ref="clientAuthenticationEntryPoint"/>  
         <custom-filter ref="clientCredentialsTokenEndpointFilter"
                           after="BASIC_AUTH_FILTER" />
        <access-denied-handler ref="oauthAccessDeniedHandler"/>  
    </http> 
    <!-- Protected resources -->
    <http pattern="/rest/**"
          create-session="never"
          entry-point-ref="oauthAuthenticationEntryPoint"
          access-decision-manager-ref="accessDecisionManager">
        <anonymous enabled="false"/>
        <intercept-url pattern="/rest/api"
                       access="ROLE_APP"/>
        <custom-filter ref="resourceServerFilter"
                       before="PRE_AUTH_FILTER"/>
        <access-denied-handler
                ref="oauthAccessDeniedHandler"/>
    </http>

    <beans:bean id="oauthAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <beans:property name="realmName" value="test"/>
    </beans:bean>

    <beans:bean id="clientAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <beans:property name="realmName" value="test/client"/>
        <beans:property name="typeName" value="Basic"/>
    </beans:bean>

    <beans:bean id="oauthAccessDeniedHandler"
          class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"/>

    <beans:bean id="clientCredentialsTokenEndpointFilter"
          class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
        <beans:property name="authenticationManager" ref="clientAuthenticationManager"/>
    </beans:bean>

    <beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
          xmlns="http://www.springframework.org/schema/beans">
        <beans:constructor-arg>
            <beans:list>
                <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter"/>
                <bean class="org.springframework.security.access.vote.RoleVoter"/>
                <bean class="org.springframework.security.access.vote.AuthenticatedVoter"/>
            </beans:list>
        </beans:constructor-arg>
    </beans:bean>

    <!-- Authentication in config file -->
    <authentication-manager id="clientAuthenticationManager">
        <authentication-provider user-service-ref="clientDetailsUserService"/>
    </authentication-manager>

    <authentication-manager alias="authenticationManager">
        <authentication-provider>
            <user-service id="userDetailsService">
                <user name="admin" password="password" authorities="ROLE_APP"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="clientDetailsUserService"
          class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <beans:constructor-arg ref="clientDetails"/>
    </beans:bean>

    <!-- Token Store  -->
    <beans:bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore"/>

    <beans:bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
        <beans:property name="tokenStore" ref="tokenStore"/>
        <beans:property name="supportRefreshToken" value="true"/>
        <beans:property name="accessTokenValiditySeconds" value="120"/>
        <beans:property name="clientDetailsService" ref="clientDetails"/>   
    </beans:bean>

    <beans:bean id="userApprovalHandler"
          class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
        <beans:property name="tokenServices" ref="tokenServices"/>
    </beans:bean>



     <!-- added -->
        <beans:bean id="oAuth2RequestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
            <constructor-arg ref="clientDetails"/>
        </beans:bean>

    <!-- Token management -->
    <oauth:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenServices"
                                user-approval-handler-ref="userApprovalHandler">
        <oauth:authorization-code/>
        <oauth:implicit/>
        <oauth:refresh-token/>
        <oauth:client-credentials/>
        <oauth:password/>
    </oauth:authorization-server>

    <oauth:resource-server id="resourceServerFilter"
                           resource-id="test"
                           token-services-ref="tokenServices"/>

    <!-- Client Definition -->
    <oauth:client-details-service id="clientDetails">

        <oauth:client client-id="restapp"
                      authorized-grant-types="authorization_code,client_credentials"
                      authorities="ROLE_APP"
                      scope="read,write,trust"
                      access-token-validity="30"
                      refresh-token-validity="600"/>


        <oauth:client client-id="restapp"  
       authorized-grant-types="password,authorization_code,refresh_token,implicit"  
       secret="restapp" authorities="ROLE_APP" /> 


    </oauth:client-details-service>

    <oauth:expression-handler id="oauthExpressionHandler" /> 
    <oauth:web-expression-handler id="oauthWebExpressionHandler"/>


</beans:beans>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30121583

复制
相关文章
Hibernate延迟加载
上一篇文章我们学习了Hibernate的多表关联关系,这里就涉及到一个很实用的概念:延迟加载或者也叫惰性加载,懒加载。使用延迟加载可以提高程序的运行效率。Java程序与数据库交互的频次越低,程序运行效率越高,所以我们应该尽量减少Java程序与数据库的交互次数,Hibernate延迟加载就很好的做到了这一点。
南风
2019/04/22
1.4K0
Hibernate延迟加载
Spring整合Hibernate、Hibernate JPA、Spring Data JPA、Spring Data Redis
环境说明,使用Jdk1.8版本,spring4.2.0.RELEASE版本、hibernate5.0.7.Final版本,spring-data-jpa-1.9.0.RELEASE版本、spring-data-redis-1.6.0.RELEASE版本。
别先生
2020/05/27
5.6K0
Hibernate之延迟加载
文章目录 1. hibernate之延迟加载 1.1. 什么是延迟加载 1.2. 好处 1.3. 如何使用延迟加载 1.4. 使用延迟加载需要注意的问题 hibernate之延迟加载 什么是延迟加载 在使用某些Hibernate方法查询数据的时候,Hibernate返回的只是一个空对象(除了id外属性都为null),并没有真正的查询数据库。而是在使用这个对象的时候才会出发查询数据,并将查询到的数据注入到这个空对象中,这种查询时机推迟到对象访问时的机制称之为延迟加载。 简单的说,使用延迟加载获取的对象,只
爱撒谎的男孩
2019/12/31
9320
hibernate延迟加载详解
hibernate延迟加载详解 Hibernae 的延迟加载是一个非常常用的技术,实体的集合属性默认会被延迟加载,实体所关联的实体默认也会被延迟加载。hibernate 通过这种延迟加载来降低系统的内存开销,从而保证 Hibernate 的运行性能。 下面先来剖析 Hibernate 延迟加载的“秘密”。 集合属性的延迟加载 当 Hibernate 从数据库中初始化某个持久化实体时,该实体的集合属性是否随持久化类一起初始化呢?如果集合属性里包含十万,甚至百万的记录,在初始化持久化实体的同时,完成所有集合属性
Java帮帮
2018/03/19
1.4K0
hibernate延迟加载详解
Spring整合Hibernate JPA
JPA:就是由Sun公司提供的一套对于持久层操作的标准(接口加文档),没有具体的实现。
害恶细君
2022/11/22
1.2K0
Hibernate延迟加载 lazy loading
/**  *  * @author XHW  *  * @date 2011-7-18  *  */ public class HibernateTest {  public static void main(String[] args) {   new HibernateTest().update();  }  public void update(){   Session session=HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();   session.beginTransaction();  Category category=(Category)session.get(Category.class, 1);   System.out.println("id:"+category.getId()+"  ,name:"+category.getName()+", description:"+category.getDescription());   Set<Product> products=category.getProducts();   session.getTransaction().commit();    } }
Hongten
2018/09/18
1.1K0
Hibernate 和 JPA
Hibernate 在 5 以后的版本中全面推进使用 JPA 的查询语法,甚至准备废弃掉自己已有的查询语法。
HoneyMoose
2022/01/13
5070
Hibernate 和 JPA
Hibernate 的延迟加载(懒加载)简介1
什么是延迟加载: 在使用某些Hibernate方法查询数据时,Hibernate返回的只是一个空对象(除id外属性都为null),并没有真正查询数据库。而在使用这个对象时才会触发查询数据库,并将查询到的数据注入到这个空对象中。这种将查询时机推迟到对象访问时的机制称之为延迟加载。 ---- 为什么要使用延迟加载: 可以提升内存资源的使用率 可以降低对数据库的访问次数 ---- 采用延迟加载的方法: session.load() 查询时不进行SQL查询,在使用对象时才执行SQL查询;效率高 query.i
qubianzhong
2018/08/10
1.4K0
JPA、Hibernate、Spring Data JPA 的关系,你懂吗?
来源:https://my.oschina.net/u/3080373/blog/1828589
Java技术栈
2019/07/31
1.8K0
Spring全家桶之SpringData——Spring 整合Hibernate与Hibernate Jpa
注意 1. sql语句 ,是通过对象查询的表 ,虽然可以出现select 但是却不能出现通配符 *,故可以省略 Select * 2 .区别 getCurrentSession 与openSession 方法的用法 getCurrentSession:当前session 必须要有事务边界, 且只能处理唯一的一个事务。当事务提交或者回滚后session 自动失效 openSession:每次都会打开一个新的session.加入每次使用多次。则获得的是不同session 对象。使用完毕后我们需要手动的调用colse方法关闭session
时间静止不是简史
2020/07/25
2.9K0
Hibernate Session和Jpa EntityManager
本文适用 Hibernate:4.3.11.Final 和 spring-data-jpa:1.10.4.RELEASE 。
pollyduan
2019/11/04
2.1K0
使用Spring Boot,JPA,Hibernate和Postgres的多租户应用程序
多租户是一种方法,应用程序实例由不同的客户使用,从而降低软件开发和部署成本,与单一租户解决方案相比,在这种解决方案中,需要触及多个部分以提供新客户端或更新现有租户。
Java架构师历程
2018/09/26
7.8K1
使用Spring Boot,JPA,Hibernate和Postgres的多租户应用程序
spring data jpa hibernate jpa 三者之间的关系
JPA规范本质上就是一种ORM规范,注意不是ORM框架——因为JPA并未提供ORM实现,它只是制订了一些规范,提供了一些编程的API接口,但具体实现则由服务厂商来提供实现,JBoss应用服务器底层就以Hibernate作为JPA的实现。
用户3148308
2018/09/13
1.3K0
spring data jpa hibernate jpa 三者之间的关系
mybatis和hibernate的以及jpa区别_hibernate sql
hibernate和mybatis是当前流行的ORM框架。hibernate对数据库结构提供了较为完整的封装。mybatis主要着力点在于java对象与SQL之间的映射关系。
全栈程序员站长
2022/09/30
1.2K0
mybatis和hibernate的以及jpa区别_hibernate sql
JPA、Hibernate、Spring data jpa之间的关系,终于明白了
全称Java Persistence API,可以通过注解或者XML描述【对象-关系表】之间的映射关系,并将实体对象持久化到数据库中。
hbbliyong
2018/07/24
1.5K0
JPA、Hibernate、Spring data jpa之间的关系,终于明白了
JPA、Hibernate、Spring data jpa之间的关系,终于明白了
全称Java Persistence API,可以通过注解或者XML描述【对象-关系表】之间的映射关系,并将实体对象持久化到数据库中。
java思维导图
2018/07/26
2.3K0
JPA、Hibernate、Spring data jpa之间的关系,终于明白了
Spring Data JPA 介绍和使用
Spring Data JPA是Spring基于Hibernate开发的一个JPA框架。如果用过Hibernate或者MyBatis的话,就会知道对象关系映射(ORM)框架有多么方便。但是Spring Data JPA框架功能更进一步,为我们做了 一个数据持久层框架几乎能做的任何事情。下面来逐步介绍它的强大功能。
乐百川
2022/05/05
3.6K0
JPA/Hibernate问题汇总
报错很明显,是由于hibernate的懒加载引起的。项目使用的是SpringBoot框架,JPA默认使用的是hibernate的实现,而hibernate的懒加载机制其实就是延迟加载对象,如果没有在session关闭前使用到对象里除id以外的属性时,就只会返回一个没有初始化过的包含了id的代理类。很多时候,这个代理类会引发上述的异常。
雨临Lewis
2022/01/12
2.6K0
spring-boot开发过程中的问题汇总
在application.properties中加上spring.jpa.properties.hibernate.default_schema=[user],由于oracle不同表空间下可以有同名表,而表的访问都是user.table,这样来区分不同表空间同名表造成的问题。
sucl
2019/08/07
1.3K0
聊聊spring data jpa的OpenSessionInView
本文主要研究一下spring data jpa的OpenSessionInView
code4it
2019/04/13
3.8K0
聊聊spring data jpa的OpenSessionInView

相似问题

为什么我的HttpClient.SendAsync被取消了?

23

绝对定位:为什么我的盒子被抵消了?

11

为什么我的地图标记ObjectAnimators被取消了?

10

为什么这个功能被取消了?

21

为什么这个孩子被抵消了?

11
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文