Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SecurityException while ndef.connect() on Android 13

Tags:

java

android

nfc

I have this code (Java) to write nfc tags:

private Tag tag;

@Override
protected void onNewIntent(Intent intent) {
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    }
}

private boolean write(String message, Tag tag) throws IOException, FormatException {
    Ndef ndef = Ndef.get(tag);
    ndef.connect();
    if (ndef.isWritable()) {
        ndef.writeNdefMessage(message);
    }
    ndef.close();
}

Said code was working until I updated my app to be compatible with the latest versions of Android.

Now running this code on Android 13 gives me the following exception:

java.lang.SecurityException: Permission Denial: Tag ( ID: XX XX XX XX XX XX XX ) is out of date
    at android.nfc.Tag.getTagService(Tag.java:388)
    at android.nfc.tech.BasicTagTechnology.connect(BasicTagTechnology.java:73)
    at android.nfc.tech.Ndef.connect(Ndef.java:71)

I understand that there is some compatibility problem but I don't know what exactly.

I am thankful for any kind of help.

UPDATE: Thanks to your feedback and some additional research I came to a solution.

I was triggering this NFC write from the onNewIntent function. It seems that it is no longer possible due to some security issues. I solved it by triggering this NFC write from the onResume function instead.

Thank you all for your help.

like image 573
autoimovil Avatar asked Aug 04 '26 20:08

autoimovil


1 Answers

This is intended by design. The problem here is that you store a tag handle and try to use it later on (maybe even after letting the user press a button or so?). You should never have done this in the first place, NFC is user interaction and you should act immediately upon scanning the tag and keep the transaction as short as possible (after all user's are not good at holding two devices constantly together for a longer period). Android finally reduced the surface of bad programming habits in that regard (see here) by making sure that your tag handle is current when you try to access a tag. This change prevents access to an invalidated tag handle once tag disconnection or a new tag discovery takes place.

like image 151
Michael Roland Avatar answered Aug 07 '26 11:08

Michael Roland