草庐IT

java - 身份验证后存储附加信息[Spring]

coder 2024-04-02 原文

我正在开发具有以下要求的 Web 应用程序:

  1. 允许用户登录
  2. 在服务器端,用户通过第 3 方 REST 网络服务进行身份验证。
  3. 如果身份验证成功,REST 网络服务将返回一个唯一的 token 和 key 。
  4. 对 REST 网络服务的任何后续请求都必须包含在第 3 点(上文)中收到的 token 。

我正在为 Web 应用程序使用 spring-mvc 和 spring security。 所以,我得到了一个有效的解决方案,但是我是 spring 的新手,不确定解决方案是否正确。

有人可以建议如果:

  1. 解决方案是否得到正确实现?
  2. 该解决方案是否以任何方式影响性能?
  3. 该解决方案是否会产生任何安全漏洞?

谢谢 :)


解决方案:

  1. 我创建了一个 MyUser 对象,用于存储从 REST 服务收到的附加信息。

    public class MyUser implements Serializable {
    
        private static final long serialVersionUID = 5047510412099091708L;
        private String RestToken;
        private String RestKey;
    
        public String getRestToken() {
            return RestToken;
        }
        public void setRestToken(String restToken) {
            RestToken = restToken;
        }
        public String getRestKey() {
            return RestKey;
        }
        public void setRestKey(String restKey) {
            RestKey = restKey;
        }
    }
    
  2. 然后我创建了一个扩展 UsernamePasswordAuthenticationToken 的 MyAuthenticationToken 对象。该对象将在 CustomAuthenticationProvider 中使用(下面的第 3 点)。

    public class MyAuthenticationToken extends UsernamePasswordAuthenticationToken {
    
            private static final long serialVersionUID = 7425814465946838862L;
            private MyUser myUser;
    
            public MyAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities, MyUser myUser){
    
                super(principal, credentials, authorities);
                this.myUser = myUser;   
            }
    
            public MyUser getMyUser() {
                return myUser;
            }
    
            public void setMyUser(MyUser myUser) {
                this.myUser = myUser;
            }
        }
    
  3. 我创建了一个自定义身份验证提供程序,它将调用 REST 服务进行身份验证,然后将附加信息存储在 myUser 和 myAuthenticationToken 对象中。

    public class CustomAuthenticationProvider implements AuthenticationProvider {
    
            @Override
            public Authentication authenticate (Authentication authentication) {
    
                MyUser myUser = new MyUser();
                MyAuthenticationToken authenticationToken = null;
                String name = authentication.getName();
                String password = authentication.getCredentials().toString();
    
                //Just an example. This section will connect to a web service in order to authenticate the client
                if (name.equals("justh") && password.equals("123456")) {
    
                    //Set the Token and Key Received from the REST WebService
                    myUser.setRestKey("RestKey");
                    myUser.setRestToken("RestToken");
    
                    List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
                    grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
    
                    authenticationToken = new MyAuthenticationToken(name, password, grantedAuths, myUser);
    
                    return authenticationToken;
                } else {
                    return null;
                }
            }
    
  4. 最后,我可以访问存储在我的 Controller 中的数据

    public ModelAndView adminPage(Authentication authentication) {
    
            MyUser user = null;
            //Get the additional data stored
            if(authentication instanceof MyAuthenticationToken){
                user = ((MyAuthenticationToken)authentication).getMyUser();
            }
    
            ModelAndView model = new ModelAndView();
            model.addObject("title", "Spring Security Hello World");
            model.addObject("message", "This is protected page - Admin Page!" + authentication.getName() + user.getRestKey() + user.getRestToken());
            model.setViewName("admin");
            return model;
        }
    

最佳答案

您的方法是正确的。只要您的要求超出简单的用户名密码身份验证流程,您就应该实现自定义 AuthenticationManagerAuthentication

但不要忘记遵守 AuthenticationManager的接口(interface)契约。

我在 webmailer 中做了一些非常相似的事情用于使用 javax.mail 对 smtp/imap 服务器进行身份验证,它可以完美地工作。

关于java - 身份验证后存储附加信息[Spring],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28010077/

有关java - 身份验证后存储附加信息[Spring]的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  6. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  7. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  8. ruby-on-rails - 带 Spring 锁的 Rails 4 控制台 - 2

    我正在使用Ruby2.1.1和Rails4.1.0.rc1。当执行railsc时,它被锁定了。使用Ctrl-C停止,我得到以下错误日志:~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`gets':Interruptfrom~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`verify_server_version'from~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.

  9. ruby-on-rails - 如何将验证与模型分开 - 2

    我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:

  10. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

随机推荐